详解C#读写Excel的几种方法
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
private void btn_Office_Click(object sender, EventArgs e)
{
string importExcelPath = "E:\import.xlsx";
string exportExcelPath = "E:\export.xlsx";
//创建
Excel.Application xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
xlApp.ScreenUpdating = false;
//打开Excel
Excel.Workbook xlsWorkBook = xlApp.Workbooks.Open(importExcelPath, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
//处理数据过程,更多操作方法自行百度
Excel.Worksheet sheet = xlsWorkBook.Worksheets[1];//工作薄从1开始,不是0
sheet.Cells[1, 1] = "test";
//另存
xlsWorkBook.SaveAs(exportExcelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//关闭Excel进程
ClosePro(xlApp, xlsWorkBook);
}
public void ClosePro(Excel.Application xlApp, Excel.Workbook xlsWorkBook)
{
if (xlsWorkBook != null)
xlsWorkBook.Close(true, Type.Missing, Type.Missing);
xlApp.Quit();
// 安全回收进程
System.GC.GetGeneration(xlApp);
IntPtr t = new IntPtr(xlApp.Hwnd); //获取句柄
int k = 0;
GetWindowThreadProcessId(t, out k); //获取进程唯一标志
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill(); //关闭进程
}