标签:
Microsoft.Office.Interop.Excel类库用于操作Excel,提供了丰富的类和函数,功能非常强大.
第一部分:类库简介
引用命名空间
using Excel = Microsoft.Office.Interop.Excel;
1,在使用类库之前,先总结以下几个类的用法
Application:Excel应用程序类,是Excel的引擎,new 一个实例。
Excel.Application excelApp = new Excel.Application();
Workbooks:Excel引擎打开的工作簿集,一个Excel引擎能够打开多个Excel 工作簿,每一个Excel 工作簿就是就是单独的Excel文档。
Excel.Workbooks wbs = excelApp.Workbooks;
Workbook:Excel引擎的一个工作簿,每一个Excel 工作簿就是就是单独的Excel文档,在工作簿上有多个sheet。
//Create New Workbook Excel.Workbook wb = wbs.Add(true); //Open existing excel Excel.Workbook wb = wbs.Add(strExcelPath);
Excel.Workbookwb = wbs.Open(strExcelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Excel.XlPlatform.xlWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing);
Worksheets:一个Workbook上的所有sheet的集合
Excel.Worksheets wss = (Excel.Worksheets)wb.Worksheets;
Excel.Worksheets wss = (Excel.Worksheets)wb.Sheets;
Worksheet:Workbook里的一个sheet,sheet的索引是从1开始的。
Excel.Worksheet wst = wss[1]; Excel.Worksheet wst = wb.Sheets.get_Item(1);
在一个Worksheet里,有Cell,Row,Column,Range,每一个Cell是由 row index 和 Column index 唯一定位的;Worksheet中的Cell还可以由字符串来唯一标识,比如“A1”,“N5”,字符表示的列名,数字表示的行号。
wst.Cells[1,1]
Range:是sheet中Cell的集合,这个集合是矩形的,由左上角和右下角的cell确定一个Range,并且每一个Cell,其实也是一个Range
Excel.Range range3 = wst.Cells[1, 1]; Excel.Range range1 = wst.get_Range("A1", "B2"); Excel.Range range2 = wst.get_Range(wst.Cells[1, 1], wst.Cells[2, 2]);
虽然Worksheet中有row和column的概念,但是并没有实际的类,可以通过Range来获取worksheet中已经使用的行和列的数目
int iRowCount = wst.UsedRange.Rows.Count; int iColumncount = wst.UsedRange.Columns.Count;
每一个Cell存储的数据,除了value之外,还有Style,Font,Formula等,可以通过Cell来绘制丰富多彩的Excel文档,也能对Cell进行合并,在这里,笔者只关注value的提取和设置。
string strGetValue = range3.Value.ToString(); range3.Value = "New String";
2,Workbook操作
2.1 新建一个Workbook
Workbooks.Add(Object Template)
Creates a new workbook. The new workbook becomes the active workbook. Returns a Workbook object.
参数 Template :Optional Object. Determines how the new workbook is created. If this argument is a string specifying the name of an existing Microsoft Excel file, the new workbook is created with the specified file as a template. If this argument is a constant, the new workbook contains a single sheet of the specified type. Can be one of the following XlWBATemplate constants: xlWBATChart, xlWBATExcel4IntlMacroSheet, xlWBATExcel4MacroSheet, or xlWBATWorksheet. If this argument is omitted, Microsoft Excel creates a new workbook with a number of blank sheets (the number of sheets is set by the SheetsInNewWorkbook property).
Excel.Workbook wb = wbs.Add(ture);
2.2 打开一个已经存在的Workbook
Excel.Workbook wb = wbs.Open(strExcelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlPlatform.xlWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing , Type.Missing, Type.Missing, Type.Missing);
3,Worksheet操作
3.1 获取一个Worksheet
Excel.Worksheet wst = wss[1]; Excel.Worksheet wst = wb.Sheets.get_Item(1);
3.2 创建一个Worksheet
wst = wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wst = wb.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
3.3 删除一个Wroksheet
wb.Worksheets[1].Delete();
4, Excel 引擎的退出
Microsoft.Office.Interop.Excel.dll 这个类在操作Excel的时候,会创建一个Microsoft Excel process,可以通过Task manager 查看,在程序中关闭Excel应用之后,还必须 kill 这个excel process。
第二部分:示例代码
public static void TestCreateExcel() { string strExcelPath = @"D:\test.xlsx"; Excel.Application excelApp = new Excel.Application(); Excel.Workbooks wbs = excelApp.Workbooks; Excel.Workbook wb = wbs.Add(true); Excel.Worksheet wst = wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing); wst.Name = "sheet_new_name"; for (int i = 1; i < 10; i++) { for (int j = 1; j < 10; j++) { Excel.Range range = wst.Cells[i, j]; range.Value = i.ToString() + "_" + j.ToString(); } } wb.SaveAs(strExcelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); CloseExcel(excelApp, wb); } public static void TestOpenExcel() { string strExcelPath = @"D:\test.xlsx"; Excel.Application excelApp = new Excel.Application(); Excel.Workbooks wbs = excelApp.Workbooks; Excel.Workbook wb = wbs.Open(strExcelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing , Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Excel.Worksheet wst = wb.Worksheets[1]; for (int i = 1; i < 10; i++) { for (int j = 1; j < 10; j++) { Excel.Range range = wst.Cells[i, j]; Console.Write(range.Value + " "); } Console.WriteLine(); } CloseExcel(excelApp, wb); } public static class KillMyExcelProcess { [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); public static void Kill(Excel.Application excel) { try { IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口 int k = 0; GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用 p.Kill(); //关闭进程k } catch (System.Exception ex) { throw ex; } } } public static void CloseExcel(Excel.Application ExcelApplication, Excel.Workbook ExcelWorkbook) { ExcelWorkbook.Close(false, Type.Missing, Type.Missing); ExcelWorkbook = null; ExcelApplication.Quit(); GC.Collect(); KillMyExcelProcess.Kill(ExcelApplication); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; using System.Runtime.InteropServices; namespace TExcel.OpCls { public class OpExcel { public void UpdateExcelColumnNameSimplify() { Excel.Application excelApp = null; Excel.Workbook xlsWorkBook = null; try { string strPath = @"C:\ExcelFile\test.xlsx"; //设置程序运行的环境 System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); //创建Application excelApp = new Excel.Application(); //设置是否显示警告窗体 excelApp.DisplayAlerts = false; //设置是否显示Excel excelApp.Visible = false; //禁止刷新屏幕 excelApp.ScreenUpdating = false; //根据路径path打开 xlsWorkBook = excelApp.Workbooks.Open(strPath, 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); //获取Worksheet对象 Excel.Worksheet xlsWorkSheet = (Excel.Worksheet)xlsWorkBook.Worksheets["sheet1"]; int colsCount = 10; for (int i = 1; i < colsCount; i++) { Excel.Range rc = (Excel.Range)xlsWorkSheet.Cells[1, i]; if (rc.Value != null) { rc.Value = rc.Value.ToString().Trim(); } } xlsWorkSheet = (Excel.Worksheet)xlsWorkBook.Worksheets["sheet2"]; for (int i = 1; i < colsCount; i++) { Excel.Range rc = (Excel.Range)xlsWorkSheet.Cells[1, i]; if (rc.Value != null) { rc.Value = rc.Value.ToString().Trim(); } } xlsWorkBook.Save(); } catch (Exception ex) { throw (ex); } finally { CloseExcel(excelApp, xlsWorkBook); } } public class KillMyExcelProcess { [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); public static void Kill(Microsoft.Office.Interop.Excel.Application excel) { try { IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口 int k = 0; GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用 p.Kill(); //关闭进程k } catch (System.Exception ex) { throw ex; } } } public void CloseExcel(Microsoft.Office.Interop.Excel.Application ExcelApplication, Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook) { ExcelWorkbook.Close(false, Type.Missing, Type.Missing); ExcelWorkbook = null; ExcelApplication.Quit(); GC.Collect(); KillMyExcelProcess.Kill(ExcelApplication); } } }
示例代码中,关于闭Excel和Kill Excel的进程的代码是从千年寒冰 博客中复制的,原文地址:
http://www.cnblogs.com/qqnnhhbb/p/3601844.html
Microsoft.Office.Interop.Excel 操作 Excel
标签:
原文地址:http://www.cnblogs.com/ljhdo/p/4539172.html