详解C#读写Excel的几种方法-创新互联
1 使用Office自带的库

前提是本机须安装office才能运行,且不同的office版本之间可能会有兼容问题,从Nuget下载 Microsoft.Office.Interop.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(); //关闭进程
}另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
名称栏目:详解C#读写Excel的几种方法-创新互联
标题链接:http://www.scyingshan.cn/article/deoidp.html


咨询
建站咨询
