Microsoft.Office.Interop.Excel.dll 是MS提供的用于操作Excel的类库,这个类库非常强大,笔者最近遇到一个项目,需要修改Excel的列名,并且做成SSIS Package,在ssms中生存job自动执行。之前考虑使用NPOI,但是在使用NPOI时,Script task不能将NPOI自动导入到.net framework,需要执行一个gacutil的脚本,有点麻烦,既然Microsoft.Office.Interop.Excel.dll是微软的东西,肯定是已经集成到.net framework中,使用起来比较方便。
示例代码如下,代码中有关闭Excel和Kill Excel的进程是从网上复制的,向前辈致敬。
using Excel = Microsoft.Office.Interop.Excel; public void UpdateExcelColumnNameSimplify() { string strPath = @"C:\ExcelFile\FY15 R-Code Master - Copy.xlsx"; Excel.Application excelApp=null; Excel.Workbook xlsWorkBook=null; try { System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); excelApp = new Excel.Application(); excelApp.DisplayAlerts = false; excelApp.Visible = false; excelApp.ScreenUpdating = false; 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); 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 { throw; } 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); }
时间: 2024-10-11 21:58:49