对于C#导入导出EXCEL文件的代码实例,以下是详细的攻略及示例说明:
1. 导出Excel文件
1.1 引用必要的命名空间
using System.IO;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
1.2 创建Excel文件
// 创建Excel对象
Application excelApp = new Application();
_Workbook workBook = excelApp.Workbooks.Add();
_Worksheet workSheet = (Worksheet)workBook.Worksheets[1];
// 填充数据
workSheet.Cells[1, 1] = "姓名";
workSheet.Cells[1, 2] = "性别";
workSheet.Cells[1, 3] = "年龄";
workSheet.Cells[2, 1] = "张三";
workSheet.Cells[2, 2] = "男";
workSheet.Cells[2, 3] = "20";
workSheet.Cells[3, 1] = "李四";
workSheet.Cells[3, 2] = "女";
workSheet.Cells[3, 3] = "18";
// 设置格式
workSheet.Rows[1].Font.Bold = true;
workSheet.Columns[1].ColumnWidth = 10;
workSheet.Columns[2].ColumnWidth = 10;
workSheet.Columns[3].ColumnWidth = 10;
1.3 保存Excel文件
// 保存文件
workBook.SaveAs("D:/test.xlsx", XlFileFormat.xlOpenXMLWorkbook);
// 释放对象
workBook.Close();
excelApp.Quit();
Marshal.ReleaseComObject(workSheet);
Marshal.ReleaseComObject(workBook);
Marshal.ReleaseComObject(excelApp);
2. 导入Excel文件
2.1 引用必要的命名空间
using System.IO;
using System.Data;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
2.2 打开Excel文件
// 创建Excel对象
Application excelApp = new Application();
_Workbook workBook = excelApp.Workbooks.Open("D:/test.xlsx");
_Worksheet workSheet = (_Worksheet)workBook.ActiveSheet;
// 获取数据
DataTable dt = new DataTable();
for (int i = 1; i <= workSheet.UsedRange.Columns.Count; i++)
{
dt.Columns.Add(workSheet.Cells[1, i].Text);
}
for (int i = 2; i <= workSheet.UsedRange.Rows.Count; i++)
{
DataRow row = dt.NewRow();
for (int j = 1; j <= workSheet.UsedRange.Columns.Count; j++)
{
row[j - 1] = workSheet.Cells[i, j].Text;
}
dt.Rows.Add(row);
}
// 释放对象
workBook.Close();
excelApp.Quit();
Marshal.ReleaseComObject(workSheet);
Marshal.ReleaseComObject(workBook);
Marshal.ReleaseComObject(excelApp);
以上就是关于C#导入导出Excel文件的完整攻略及代码示例说明。在导出方面,我们需要依赖Microsoft.Office.Interop.Excel库,同时需要创建Excel对象、填充数据、设置格式和保存文件等步骤。在导入方面,同样需要依赖Microsoft.Office.Interop.Excel库,然后打开Excel文件,获取数据并释放对象。
希望这些示例能对你有所帮助!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#导入导出EXCEL文件的代码实例 - Python技术站