C# 操作excel

来源:互联网 发布:三维设计软件 编辑:程序博客网 时间:2024/06/16 12:44

参考来源http://blog.csdn.net/dream_follower/article/details/70339849

1.添加引用 Microsoft.Office.Interop.Excel 15.0.0.0版本

2.添加声明

using Microsoft.Office.Interop.Excel;using Excel = Microsoft.Office.Interop.Excel;using System.Data.OleDb;using System.Diagnostics;

//读取  (只读)

//取得指定或活动工作簿中所有表单的集合。只读Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();_Workbook _wbk = app.Workbooks.Add(@"C:\Users\Desktop\123.xlsx");Sheets shs = _wbk.Sheets;                                   _Worksheet _wsh = (_Worksheet)shs.get_Item(1);              //获取下标工作表句柄int rowsint = _wsh.UsedRange.Cells.Rows.Count;              //得到行数int columnsint = _wsh.UsedRange.Cells.Columns.Count;        //得到列数Range r = _wsh.Range[_wsh.Cells[1, 1], _wsh.Cells[2, 2]];   //获取单元格范围string gdas34 = r.Value2[1,1];                              //获取内部值

//写入  (读写)

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();object missing = System.Reflection.Missing.Value;//创建Excel对象Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(@"C:\Users\Desktop\123.xlsx", missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);//取得工作薄内第一个工作表Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1);ws.Cells[4, 7] = "4213"; //单元格赋值ws.get_Range("C7", "D8").Value = r.Value;//范围粘贴赋值wb.Save();excelApp.Quit();wb = null;ws = null;excelApp = null;Process[] procs = Process.GetProcessesByName("excel");foreach (Process pro in procs){    pro.Kill();//没有更好的方法,只有杀掉进程}GC.Collect();


原创粉丝点击