没有合适的资源?快使用搜索试试~ 我知道了~
首页详解C#读写Excel的几种方法
资源详情
资源评论
资源推荐

详解详解C#读写读写Excel的几种方法的几种方法
主要介绍了详解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(); //关闭进程
}
2. 使用使用NPOI
地址:https://github.com/tonyqus/npoi
在不安装office的时候也是可以读写的,速度很快,从Nuget下载 NPOI
读写代码如下:
using System.IO;
using NPOI;
using NPOI.SS.UserModel;
private void btn_NPOI_Click(object sender, EventArgs e)
{
string importExcelPath = "E:\import.xlsx";
string exportExcelPath = "E:\export.xlsx";
IWorkbook workbook = WorkbookFactory.Create(importExcelPath);
ISheet sheet = workbook.GetSheetAt(0);//获取第一个工作薄
IRow row = (IRow)sheet.GetRow(0);//获取第一行
//设置第一行第一列值,更多方法请参考源官方Demo
row.CreateCell(0).SetCellValue("test");//设置第一行第一列值
//导出excel
FileStream fs = new FileStream(exportExcelPath, FileMode.Create, FileAccess.ReadWrite);
workbook.Write(fs);
fs.Close();
}
3. 使用使用ClosedXml
地址:https://github.com/ClosedXML/ClosedXML
从Nuget下载ClosedXml










安全验证
文档复制为VIP权益,开通VIP直接复制

评论0