话说在四年前,我做过一个项目也是跟Excel控制有关的
那时候做的是从Excel中读出资料,并将数据中的档案跟路径,将指定的档案上传到微软的Share Point Server....
那时候我原本也是使用Microsoft.Office.Interop.Excel,项目也完成了
同时主管也教我如何透过OleDB当成数据库读,那就两种方法都会用了....
另外一个项目就是利用OWC来控制Office
这次又在论坛看到,让我觉得很怀念
那刚好顺便整理整理这些资料
这段代码示范了如何开启Excel
using System; using System.Reflection; using Microsoft.Office.Interop.Excel; public class CreateExcelWorksheet { static void Main() { Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct."); return; } xlApp.Visible = true; Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); Worksheet ws = (Worksheet)wb.Worksheets[1]; if (ws == null) { Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct."); } // Select the Excel cells, in the range c1 to c7 in the worksheet. Range aRange = ws.get_Range("C1", "C7"); if (aRange == null) { Console.WriteLine("Could not get a range. Check to be sure you have the correct versions of the office DLLs."); } // Fill the cells in the C1 to C7 range of the worksheet with the number 6. Object[] args = new Object[1]; args[0] = 6; aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args); // Change the cells in the C1 to C7 range of the worksheet to the number 8. aRange.Value2 = 8; } }
如何使用Excel
using Microsoft.Office.Interop.Excel; //引用Excel Application類別 _Application myExcel = null; //引用活頁簿類別 _Workbook myBook = null; //引用工作表類別 _Worksheet mySheet = null; //引用Range類別 Range myRange = null; //開啟一個新的應用程式 myExcel = new Microsoft.Office.Interop.Excel.Application(); //加入新的活頁簿 myExcel.Workbooks.Add(true); //停用警告訊息 myExcel.DisplayAlerts = false; //讓Excel文件可見 myExcel.Visible = true; //引用第一個活頁簿 myBook = myExcel.Workbooks[1]; //設定活頁簿焦點 myBook.Activate(); //引用第一個工作表 mySheet = (_Worksheet)myBook.Worksheets[1]; //命名工作表的名稱為 "Array" mySheet.Name = "Cells"; //設工作表焦點mySheet.Activate(); //用offset寫入陣列資料 myRange = mySheet.get_Range("A2", Type.Missing); myRange.get_Offset(i, j).Select();myRange.Value2 = "'" + myData[i, j]; //用Cells寫入陣列資料 myRange.get_Range(myExcel.Cells[2 + i, 1 + j], myExcel.Cells[2 + i, 1 + j]).Select(); myExcel.Cells[2 + i, 1 + j] = "'" + myData[i, j]; //加入新的工作表在第1張工作表之後 myBook.Sheets.Add(Type.Missing, myBook.Worksheets[1], 1, Type.Missing); //引用第2個工作表 mySheet = (_Worksheet)myBook.Worksheets[2]; //命名工作表的名稱為 "Array" mySheet.Name = "Array"; //加入新的工作表在第1張工作表之後 myBook.Sheets.Add(Type.Missing, myBook.Worksheets[1], 1, Type.Missing); //引用第2個工作表 mySheet = (_Worksheet)myBook.Worksheets[2]; //命名工作表的名稱為 "Array" mySheet.Name = "Array"; //寫入報表名稱 myExcel.Cells[1, 4] = "普通報表"; //設定範圍 myRange=(Range)mySheet.get_Range(myExcel.Cells[2, 1], myExcel.Cells[UpBound1 + 1, UpBound2 + 1]); myRange.Select(); //用陣列一次寫入資料 myRange.Value2 = "'" + myData; //設定儲存路徑 string PathFile = Directory.GetCurrentDirectory() + @"/button4.xls"; //另存活頁簿 myBook.SaveAs(PathFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing , XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, ype.Missing,Type.Missing,Type.Missing); //關閉活頁簿 myBook.Close(false, Type.Missing, Type.Missing); //關閉Excel myExcel.Quit(); //釋放Excel資源 System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel); myBook = null; mySheet = null; myRange = null; myExcel = null; GC.Collect();
这段代码示范如何用C#处理Excel的事件
//Excel Automation variables: Excel.Application xlApp; Excel.Workbook xlBook; Excel.Worksheet xlSheet1, xlSheet2, xlSheet3; //Excel event delegate variables: Excel.AppEvents_WorkbookBeforeCloseEventHandler EventDel_BeforeBookClose; Excel.DocEvents_ChangeEventHandler EventDel_CellsChange; private void StartExcelAndSinkEvents() { //Start Excel, and then create a new workbook. xlApp = new Excel.Application(); xlBook = xlApp.Workbooks.Add( Missing.Value ); xlBook.Windows.get_Item(1).Caption = "XL Event Test"; xlSheet1 = (Excel.Worksheet)xlBook.Worksheets.get_Item(1); xlSheet2 = (Excel.Worksheet)xlBook.Worksheets.get_Item(2); xlSheet3 = (Excel.Worksheet)xlBook.Worksheets.get_Item(3); xlSheet1.Activate(); //Add an event handler for the WorkbookBeforeClose Event of the //Application object. EventDel_BeforeBookClose = new Excel.AppEvents_WorkbookBeforeCloseEventHandler( BeforeBookClose); xlApp.WorkbookBeforeClose += EventDel_BeforeBookClose; //Add an event handler for the Change event of both worksheet objects. EventDel_CellsChange = new Excel.DocEvents_ChangeEventHandler( CellsChange); xlSheet1.Change += EventDel_CellsChange; xlSheet2.Change += EventDel_CellsChange; xlSheet3.Change += EventDel_CellsChange; //Make Excel visible and give the user control. xlApp.Visible = true; xlApp.UserControl = true; } private void CellsChange(Excel.Range Target ) { //This is called when any cell on a worksheet is changed. Debug.WriteLine("Delegate: You Changed Cells " + Target.get_Address( Missing.Value, Missing.Value, Excel.XlReferenceStyle.xlA1, Missing.Value, Missing.Value ) + " on " + Target.Worksheet.Name); } private void BeforeBookClose(Excel.Workbook Wb, ref bool Cancel ) { //This is called when you choose to close the workbook in Excel. //The event handlers are removed, and then the workbook is closed //without saving the changes. Wb.Saved = true; Debug.WriteLine("Delegate: Closing the workbook and removing event handlers."); xlSheet1.Change -= EventDel_CellsChange; xlSheet2.Change -= EventDel_CellsChange; xlSheet3.Change -= EventDel_CellsChange; xlApp.WorkbookBeforeClose -= EventDel_BeforeBookClose; }
Read Excel with OLEDB
using System.Data; using System.Data.OleDb; ... String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + [Your Excel File Name Here] + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(sConnectionString); objConn.Open(); OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM [Sheet1$]", objConn); OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); objAdapter1.SelectCommand = objCmdSelect; DataSet objDataset1 = new DataSet(); objAdapter1.Fill(objDataset1); objConn.Close();