/**
* 定义时间格式化对象
*/
public static DateFormat dfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 获取Excel单元格字符串值
*
* @param cell
* Excel单元格
* @return 返回单元格的字符串值
*/
public static String getCellValue(Cell cell) {
// 定义单元格字符串值对象
String value = null;
// 判断单元格是否为空
if (cell != null) {
// 根据单元格数据类型获取字符串值
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
// 空单元格返回空字符串
value = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
// 布尔型单元格返回布尔字符串
value = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
// 无效单元格返回空
value = null;
break;
case Cell.CELL_TYPE_FORMULA:
// 函数单元格返回函数计算结果字符串
Workbook wb = cell.getSheet().getWorkbook();
CreationHelper crateHelper = wb.getCreationHelper();
FormulaEvaluator evaluator = crateHelper.createFormulaEvaluator();
value = getCellValue(evaluator.evaluateInCell(cell));
break;
case Cell.CELL_TYPE_NUMERIC:
// 数值单元格返回数值字符串
if (DateUtil.isCellDateFormatted(cell)) {
Date theDate = cell.getDateCellValue();
value = dfDateTime.format(theDate);
} else {
value = NumberToTextConverter.toText(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
// 字符串单元格返回字符串
value = cell.getRichStringCellValue().getString();
break;
default:
// 其他返回空
value = null;
}
}
// 返回单元格字符串值
return value;
}
标签: Excel
办公软件
关于C#中使用NPOI组件读写Excel文件的说明
使用NPOI可以在没有安装Office或者相应环境的机器上对Excel文档进行读写。其下载地址为:http://npoi.codeplex.com/releases
一、读取Excel文件:
// 定义要读取的Excel文件地址
string excel = @"C:\test.xls";
// 定义要写入的数据表
DataTable dataTable = new DataTable();
// 创建Excel文件流
FileStream fileStream = new FileStream(excel, FileMode.Open, FileAccess.Read);
// 通过Excel文件流创建NPOI的Excel操作对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fileStream);
// 关闭Excel文件流
fileStream.Close();
// 获取Excel工作表
ISheet sheet = hssfWorkbook.GetSheetAt(0);
// 获取Excel工作表的行枚举对象
IEnumerator rows = sheet.GetRowEnumerator();
// 是否存在第一行
if (rows.MoveNext())
{
// 获取第一行
HSSFRow hssfRow = (HSSFRow)rows.Current;
// 遍历行数据设置数据表列名
for (int j = 0, length = hssfRow.LastCellNum; j < length; j++)
{
// 获取单元格
ICell cell = hssfRow.GetCell(j);
if (cell != null)
{
// 设置数据表列名
dataTable.Columns.Add(cell.ToString());
}
}
// 循环获取行数据
while (rows.MoveNext())
{
// 获取当前行
hssfRow = (HSSFRow)rows.Current;
// 创建数据表行
DataRow dataRow = dataTable.NewRow();
// 遍历行数据设置数据表行数据
for (int i = 0, length = hssfRow.LastCellNum; i < length; i++)
{
// 获取单元格
ICell cell = hssfRow.GetCell(i);
if (cell != null)
{
// 设置数据表行数据
dataRow[i] = cell.ToString();
}
}
// 添加数据行到数据表中
dataTable.Rows.Add(dataRow);
}
}
// 关闭NPOI的Excel操作对象
hssfWorkbook.Close();
二、写入Excel文件:
// 定义要读取的数据表
DataTable dataTable = new DataTable();
// 定义要写入的Excel文件地址
string excel = @"C:\test.xls";
// 创建NPOI的Excel操作对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
// 根据数据表名创建Excel工作表
ISheet sheet = hssfWorkbook.CreateSheet(dataTable.TableName);
// 创建工作表第一行
IRow row = sheet.CreateRow(0);
// 遍历数据表列名写入工作表第一行
for (int i = 0, length = dataTable.Columns.Count; i < length; i++)
{
// 创建工作表单元格并写入列名
row.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
}
// 遍历数据表行数据写入工作表
for (int i = 0, iLength = dataTable.Rows.Count; i < iLength; i++)
{
//创建工作表数据行
IRow row2 = sheet.CreateRow(i + 1);
// 遍历行数据写入工作表
for (int j = 0, jLength = dataTable.Columns.Count; j < jLength; j++)
{
// 获取数据
object value = dataTable.Rows[i][j];
// 创建单元格
ICell cell = row2.CreateCell(j);
// 设置单元格数据
if (value == null)
{
cell.SetCellValue("");
}
else
{
cell.SetCellValue(value.ToString());
}
}
}
// 创建Excel文件流
FileStream fileStream = new FileStream(excel, FileMode.Create, FileAccess.Write);
// 将Excel数据写入文件流
hssfWorkbook.Write(fileStream);
// 将文件流数据写入到文件中
fileStream.Flush();
// 关闭Excel文件流
fileStream.Close();
// 关闭NPOI的Excel操作对象
hssfWorkbook.Close();
更多信息请参阅:NPOI – Home
关于C#中调用Excel程序后强制关闭其进程的说明
在C#中使用Microsoft.Office.Interop.Excel.dll操作Excel文件时,有时创建的Application无法正常退出,因此我们就需要通过结束其进程的方式强制将Excel的Application退出:
一、引入Windows API获取进程Id函数:
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int id);
二、强制结束Excel的Application进程:
// 创建Excel进程
Microsoft.Office.Interop.Excel.Application app = new Application();
try
{
// 正常退出Excel进程
app.Quit();
}
catch
{
// 如Excel进程退出失败,则强制结束其进程
// 获取当前Excel进程的句柄
IntPtr intPtr = new IntPtr(app.Hwnd);
// 获取当前Excel进程的进程Id
int processId = 0;
GetWindowThreadProcessId(intPtr, out processId);
// 获取当前Excel进程
Process process = Process.GetProcessById(processId);
if (process != null)
{
// 强制结束Excel进程
process.Kill();
}
}
关于C#中读写Microsoft Office Excel的说明
Application方式读写
添加COM程序集引用:Microsoft Excel 14.0 Object Library
添加using:Microsoft.Office.Interop.Excel
一、读取DataTable数据:
// 定义数据存储表
DataTable dataTable = new DataTable();
// Excel文件路径
string file = "C:/data.xls";
// 打开Excel应用程序
Application app = new Application();
// 设置Excel应用程序不可见
app.Visible = false;
// 读取Excel工作簿
Workbooks books = app.Workbooks;
_Workbook book = books.Add(file);
// 读取Excel工作表
Sheets sheets = book.Worksheets;
_Worksheet sheet = sheets.get_Item(1) as _Worksheet;
// 读取列名
for (int i = 0, length = sheet.Columns.Count; i < length; i++)
{
dataTable.Columns.Add(sheet.Cells[1, i + 1].ToString());
}
// 读取行数据
for (int i = 0, iLength = sheet.Rows.Count; i < iLength; i++)
{
object[] obj = new object[sheet.Columns.Count];
for (int j = 0, jLength = sheet.Columns.Count; j < jLength; j++)
{
obj[j] = sheet.Cells[i + 2, j + 1];
}
dataTable.Rows.Add(obj);
}
// 不保存原始数据状态下关闭Excel应用程序
app.UserControl = false;
app.Quit();
return dataTable;
二、写入DataTable数据:
// 要写入的数据表
DataTable dataTable = new DataTable();
// Excel文件保存路径
string file = "C:/data.xls";
// 打开Excel应用程序
Application app = new Application();
// 设置Excel应用程序不可见
app.Visible = false;
// 读取Excel工作簿
Workbooks books = app.Workbooks;
_Workbook book = books.Add(XlWBATemplate.xlWBATWorksheet);
// 读取Excel工作表
Sheets sheets = book.Worksheets;
_Worksheet sheet = sheets.get_Item(1) as _Worksheet;
// 写入列名
for (int i = 0, length = dataTable.Columns.Count; i < length; i++)
{
sheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
}
// 写入行数据
for (int i = 0, iLength = dataTable.Rows.Count; i < iLength; i++)
{
for (int j = 0, jLength = dataTable.Columns.Count; j < jLength; j++)
{
sheet.Cells[i + 2, j + 1] = dataTable.Rows[i][j].ToString();
}
}
// 保存Excel工作簿
book.SaveCopyAs(file);
book.Saved = true;
// 关闭Excel应用程序
app.UserControl = false;
app.Quit();
ADO.NET方式读写
一、获取Sheet名:
// 定义Sheet数据表名存储数组
string[] sheets = new string[] { };
// Excel文件路径
string file = "C:/data.xls";
// OleDb链接字符串
string connection = "Provider=Microsoft.Jet.OLEDB.4.0;";
connection += "Data Source=" + file + ";";
connection += "Extended Properties=Excel 8.0;";
// 打开OleDb链接
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
// 读取数据架构信息
DataTable dataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// 读取Sheet数据表名
sheets = new string[dataTable.Rows.Count];
for (int i = 0, length = dataTable.Rows.Count; i < length; i++)
{
sheets[i] = dataTable.Rows[i]["TABLE_NAME"].ToString();
}
// 关闭OleDb链接
con.Close();
}
return sheets;
二、读取DataTable数据:
// 定义数据存储表
DataTable dataTable = new DataTable();
// Excel文件路径
string file = "C:/data.xls";
// OleDb链接字符串
string connection = "Provider=Microsoft.Jet.OLEDB.4.0;";
connection += "Data Source=" + file + ";";
connection += "Extended Properties=Excel 8.0;";
// 打开OleDb链接
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
// 查询对应Sheet数据表的数据
string sql = "select * from [sheet$]";
// 读取表数据
using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, con))
{
adapter.Fill(dataTable);
}
// 关闭OleDb链接
con.Close();
}
return dataTable;