//1.添加引用-〉com-〉microsoft excel 11.0 //2.若出現錯誤:命名空間「Microsoft.Office」中不存在類型或命名空間名稱「Interop」(是缺乏程序集引用嗎?) //解決方法:先刪除引用中的Excel,而後找到文件Microsoft.Office.Interop.Excel.dll,手動添加該文件的引用 using System; using System.Data; using System.Reflection; using System.IO; using Microsoft.Office.Core; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace Wage.Common { /// <summary> /// 做者 Li Aimin (原創) /// 功能描述:C#對Excel報表進行操做 /// 建立時間:2006-01-17, 修改時間:2007-1-14 /// 說明:在工程中須要添加 Excel11.0對象庫的引用(Office 2000爲Excel9.0,Office XP爲Excel10.0); /// 須要在Dcom中配置Excel應用程序的權限; /// 服務器須要安裝Office2003 /// </summary> public class ExcelLib { //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrgrfexcelapplicationobject.asp #region Variables private Excel.Application excelApplication = null; private Excel.Workbooks excelWorkBooks = null; private Excel.Workbook excelWorkBook = null; private Excel.Worksheet excelWorkSheet = null; private Excel.Range excelRange = null;//Excel Range Object,多種用途 private Excel.Range excelCopySourceRange = null;//Excel Range Object private int excelActiveWorkSheetIndex; //活動工做表索引 private string excelOpenFileName = ""; //操做Excel的路徑 private string excelSaveFileName = ""; //保存Excel的路徑 #endregion #region Properties public int ActiveSheetIndex { get { return excelActiveWorkSheetIndex; } set { excelActiveWorkSheetIndex = value; } } public string OpenFileName { get { return excelOpenFileName; } set { excelOpenFileName = value; } } public string SaveFileName { get { return excelSaveFileName; } set { excelSaveFileName = value; } } #endregion // //-------------------------------------------------------------------------------------------------------- /// <summary> /// 構造函數; /// </summary> public ExcelLib() { excelApplication = null;//Excel Application Object excelWorkBooks = null;//Workbooks excelWorkBook = null;//Excel Workbook Object excelWorkSheet = null;//Excel Worksheet Object ActiveSheetIndex = 1; //默認值活動工做簿爲第一個;設置活動工做簿請參閱SetActiveWorkSheet() } /// <summary> /// 以excelOpenFileName爲模板新建Excel文件 /// </summary> public bool OpenExcelFile() { if (excelApplication != null) CloseExcelApplication(); //檢查文件是否存在 if (excelOpenFileName == "") { throw new Exception("請選擇文件!"); } if (!File.Exists(excelOpenFileName)) { throw new Exception(excelOpenFileName + "該文件不存在!");//該異常如何處理,由什麼處理???? } try { excelApplication = new Excel.ApplicationClass(); excelWorkBooks = excelApplication.Workbooks; excelWorkBook = ((Excel.Workbook)excelWorkBooks.Open(excelOpenFileName, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[excelActiveWorkSheetIndex]; excelApplication.Visible = false; return true; } catch (Exception e) { CloseExcelApplication(); MessageBox.Show("(1)沒有安裝Excel 2003;(2)或沒有安裝Excel 2003 .NET 可編程性支持;\n詳細信息:" +e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //throw new Exception(e.Message); return false; } } /// <summary> /// 讀取一個Cell的值 /// </summary> /// <param name="CellRowID">要讀取的Cell的行索引</param> /// <param name="CellColumnID">要讀取的Cell的列索引</param> /// <returns>Cell的值</returns> public string getOneCellValue(int CellRowID, int CellColumnID) { if (CellRowID <= 0) { throw new Exception("行索引超出範圍!"); } string sValue = ""; try { sValue = ((Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]).Text.ToString(); } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } return (sValue); } /// <summary> /// 讀取一個連續區域的Cell的值(矩形區域,包含一行或一列,或多行,多列),返回一個一維字符串數組。 /// </summary> /// <param name="StartCell">StartCell是要寫入區域的左上角單元格</param> /// <param name="EndCell">EndCell是要寫入區域的右下角單元格</param> /// <returns>值的集合</returns> public string[] getCellsValue(string StartCell, string EndCell) { string[] sValue = null; //try //{ excelRange = (Excel.Range)excelWorkSheet.get_Range(StartCell, EndCell); sValue = new string[excelRange.Count]; int rowStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Row; //起始行號 int columnStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Column; //起始列號 int rowNum = excelRange.Rows.Count; //行數目 int columnNum = excelRange.Columns.Count; //列數目 int index = 0; for (int i = rowStartIndex; i < rowStartIndex + rowNum; i++) { for (int j = columnStartIndex; j < columnNum + columnStartIndex; j++) { //讀到空值null和讀到空串""分別處理 sValue[index] = ((Excel.Range)excelWorkSheet.Cells[i, j]).Text.ToString(); index++; } } //} //catch (Exception e) //{ // CloseExcelApplication(); // throw new Exception(e.Message); //} return (sValue); } /// <summary> /// 讀取全部單元格的數據(矩形區域),返回一個datatable.假設全部單元格靠工做表左上區域。 /// </summary> public DataTable getAllCellsValue() { int columnCount = getTotalColumnCount(); int rowCount = getTotalRowCount(); DataTable dt = new DataTable(); //設置datatable列的名稱 for (int columnID = 1; columnID <= columnCount; columnID++) { dt.Columns.Add(((Excel.Range)excelWorkSheet.Cells[1, columnID]).Text.ToString()); } for (int rowID = 2; rowID <= rowCount; rowID++) { DataRow dr = dt.NewRow(); for (int columnID = 1; columnID <= columnCount; columnID++) { dr[columnID - 1] = ((Excel.Range)excelWorkSheet.Cells[rowID, columnID]).Text.ToString(); //讀到空值null和讀到空串""分別處理 } dt.Rows.Add(dr); } return (dt); } public int getTotalRowCount() {//當前活動工做表中有效行數(總行數) int rowsNumber = 0; try { while (true) { if (((Excel.Range)excelWorkSheet.Cells[rowsNumber + 1, 1]).Text.ToString().Trim() == "" && ((Excel.Range)excelWorkSheet.Cells[rowsNumber + 2, 1]).Text.ToString().Trim() == "" && ((Excel.Range)excelWorkSheet.Cells[rowsNumber + 3, 1]).Text.ToString().Trim() == "") break; rowsNumber++; } } catch { return -1; } return rowsNumber; } /// <summary> /// 當前活動工做表中有效列數(總列數) /// </summary> /// <param></param> public int getTotalColumnCount() { int columnNumber = 0; try { while (true) { if (((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 1]).Text.ToString().Trim() == "" && ((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 2]).Text.ToString().Trim() == "" && ((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 3]).Text.ToString().Trim() == "") break; columnNumber++; } } catch { return -1; } return columnNumber; } /// <summary> /// 向一個Cell寫入數據 /// </summary> /// <param name="CellRowID">CellRowID是cell的行索引</param> /// <param name="CellColumnID">CellColumnID是cell的列索引</param> ///<param name="Value">要寫入該單元格的數據值</param> public void setOneCellValue(int CellRowID, int CellColumnID, string Value) { try { excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.Value2 = Value;//Value2? //Gets or sets the value of the NamedRange control. //The only difference between this property and the Value property is that Value2 is not a parameterized property. excelRange = null; } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } /// <summary> /// 設置活動工做表 /// </summary> /// <param name="SheetIndex">要設置爲活動工做表的索引值</param> public void SetActiveWorkSheet(int SheetIndex) { if (SheetIndex <= 0) { throw new Exception("索引超出範圍!"); } try { ActiveSheetIndex = SheetIndex; excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[ActiveSheetIndex]; } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } /// <summary> /// 向連續區域一次性寫入數據;只有在區域連續和寫入的值相同的狀況下可使用方法 /// </summary> /// <param name="StartCell">StartCell是要寫入區域的左上角單元格</param> /// <param name="EndCell">EndCell是要寫入區域的右下角單元格</param> /// <param name="Value">要寫入指定區域全部單元格的數據值</param> public void setCellsValue(string StartCell, string EndCell, string Value) { try { excelRange = excelWorkSheet.get_Range(StartCell, EndCell); excelRange.Value2 = Value; excelRange = null; } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } /// <summary> /// 給一行寫數據 /// </summary> public void setOneLineValues(int LineID, int StartCellColumnID, int EndCellColumnID, string[] Values)////已經測試 { //用1-19號元素 //if (Values.Length!=EndCellColumnID-StartCellColumnID) //{ // throw new Exception("單元格數目與提供的值的數目不一致!"); //} for (int i = StartCellColumnID; i <= EndCellColumnID; i++) { setOneCellValue(LineID, i, Values[i]); } } public void setCellsBorder(string startCell, string endCell) { //設置某個範圍內的單元格的邊框 excelRange = excelWorkSheet.get_Range(startCell, endCell); excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous; //excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous; } public void setOneCellBorder(int CellRowID, int CellColumnID) { //設置某個單元格的邊框 excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous; excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous; //excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous; //excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous; } public void SetColumnWidth(string startCell, string endCell, int size) { //設置某個範圍內的單元格的列的寬度 excelRange = excelWorkSheet.get_Range(startCell, endCell); excelRange.ColumnWidth = size; } public void SetOneCellFont(int CellRowID, int CellColumnID, string fontName, int fontSize) { excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.Font.Name = fontName; excelRange.Font.Size = fontSize; } public void SetOneCellHorizontalAlignment(int CellRowID, int CellColumnID, Excel.Constants alignment) { excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.HorizontalAlignment = alignment; } public void SetOneCellColumnWidth(int CellRowID, int CellColumnID, int size) { //設置某個單元格的列的寬度 excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.ColumnWidth = size; } /// <summary> /// 設置一個Cell的數據格式 /// </summary> /// <param name="CellRowID">CellRowID是cell的行索引</param> /// <param name="CellColumnID">CellColumnID是cell的列索引</param> ///<param name="Value">數據格式</param> public void setOneCellNumberFormat(int CellRowID, int CellColumnID, string numberFormat) { try { excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.NumberFormatLocal = numberFormat; excelRange = null; } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } public void SetRowHeight(string startCell, string endCell, int size) { //設置某個範圍內的單元格的行的高度 excelRange = excelWorkSheet.get_Range(startCell, endCell); excelRange.RowHeight = size; } public void SetRowHeight(int CellRowID, int CellColumnID, float size) { //設置某個範圍內的單元格的行的高度 excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.RowHeight = size; } public void SetOneCellRowHeight(int CellRowID, int CellColumnID, int size) { //設置某個單元格的行的高度 excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]; excelRange.RowHeight = size; } /// <summary> /// 拷貝區域.限制:在同一個工做表中複製 /// </summary> /// <param name="SourceStart">源區域的左上角單元格</param> /// <param name="SourceEnd">源區域的右下角單元格</param> /// <param name="DesStart">目標區域的左上角單元格</param> /// <param name="DesEnd">目標區域的右下角單元格</param> public void CopyCells(string SourceStart, string SourceEnd, string DesStart, string DesEnd) { try { excelCopySourceRange = excelWorkSheet.get_Range(SourceStart, SourceEnd); excelRange = excelWorkSheet.get_Range(DesStart, DesEnd); excelCopySourceRange.Copy(excelRange); excelCopySourceRange = null; excelRange = null; } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } public void CopyWorksheet(int SourceWorksheetIndex, int DesWorksheetIndex) { try { // Sheets("Sheet2").Select //Sheets("Sheet2").Copy After:=Sheets(3) Excel.Worksheet sheetSource = (Excel.Worksheet)excelWorkBook.Worksheets[SourceWorksheetIndex]; sheetSource.Select(Missing.Value); Excel.Worksheet sheetDest = (Excel.Worksheet)excelWorkBook.Worksheets[DesWorksheetIndex]; sheetSource.Copy(Missing.Value, sheetDest); } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } /// <summary> /// 插入一行 /// </summary> /// <param name="CellRowID">要插入所在行的索引位置,插入後其原有行下移</param> /// <param name="RowNum">要插入行的個數</param> public void InsertRow(int CellRowID, int RowNum)//插入空行 { if (CellRowID <= 0) { throw new Exception("行索引超出範圍!"); } if (RowNum <= 0) { throw new Exception("插入行數無效!"); } try { excelRange = (Excel.Range)excelWorkSheet.Rows[CellRowID, Missing.Value]; for (int i = 0; i < RowNum; i++) { excelRange.Insert(Excel.XlDirection.xlDown, Missing.Value); } excelRange = null; } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } /// <summary> /// 保存Excel文件 /// </summary> public Excel.Range FindFirstRange(Excel.Range xlRange, string FindText)//查找//沒有測試 { //查找第一個知足的區域 //Search for the first match Excel.Range firstFind = null; firstFind = xlRange.Find(FindText, Missing.Value, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Missing.Value, Missing.Value); return firstFind; //若是沒找到,返回空 } //http://msdn.microsoft.com/library/en-us/dv_wrcore/html/wrtskHowToSearchForTextInWorksheetRanges.asp?frame=true /// <summary> /// 當前活動工做表中有效行數(總行數) /// </summary> /// <param></param> /// <summary> /// 判斷單元格是否有數據 /// </summary> public bool CellValueIsNull(int CellLineID, int CellColumnID)////已經測試 { //判斷單元格是否有數據 if ((((Excel.Range)excelWorkSheet.Cells[CellLineID, CellColumnID]).Text.ToString().Trim() != "")) return false; return true; } public void newWorkbook(string excelTemplate, string fileName) { //以excelTemplate爲模板新建文件fileName //excelApplication. excelWorkBook = excelWorkBooks.Add(excelTemplate); SaveFileName = ""; SaveExcel(); } public void newWorksheet() { excelWorkBook.Worksheets.Add(Missing.Value, Missing.Value, 1, Missing.Value); } public void setWorksheetName(int sheetIndex, string worksheetName) { // Missing.Value Excel._Worksheet sheet = (Excel._Worksheet)(excelWorkBook.Worksheets[(object)sheetIndex]); sheet.Name = worksheetName; } public void mergeOneLineCells(string startCell, string endCell) { //合併一行單元格 excelRange = excelWorkSheet.get_Range(startCell, endCell); //excelRange.Merge(true); excelRange.MergeCells = true; } public void HorizontalAlignmentCells(string startCell, string endCell, Excel.Constants alignment) { //水平對齊一行單元格 excelRange = excelWorkSheet.get_Range(startCell, endCell); excelRange.HorizontalAlignment = alignment; } public void VerticalAlignmentCells(string startCell, string endCell, Excel.Constants alignment) { //垂直對齊一行單元格 excelRange = excelWorkSheet.get_Range(startCell, endCell); excelRange.VerticalAlignment = alignment; } //實現列號-〉字母 (26-〉Z,27->AA) private string ConvertColumnIndexToChar(int columnIndex) { if (columnIndex < 1 || columnIndex > 256) { MessageBox.Show("columnIndex=" + columnIndex + ",超出了有效範圍(1-256)"); return "A"; } if (columnIndex >= 1 && columnIndex <= 26)//1--26 { return "AA"; } if (columnIndex >= 27 && columnIndex <= 256)//27--256 { return "AA"; } return "A"; } //字母-〉列號 Z-〉26 public void SaveExcel() { if (excelSaveFileName == "") { throw new Exception("未指定要保存的文件名"); } try { //excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value); excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value); } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } //-------------------------------------------------------------------------------------------------------- /// <summary> /// 保存Excel文件,格式xml. /// </summary> public void SaveExcelAsXML() { if (excelSaveFileName == "") { throw new Exception("未指定要保存的文件名"); } try { //excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value); excelWorkSheet.SaveAs(excelSaveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value); } catch (Exception e) { CloseExcelApplication(); throw new Exception(e.Message); } } //-------------------------------------------------------------------------------------------------------- /// <summary> /// 關閉Excel文件,釋放對象;最後必定要調用此函數,不然會引發異常 /// </summary> /// <param></param> public void CloseExcelApplication() { try { excelWorkBooks = null; excelWorkBook = null; excelWorkSheet = null; excelRange = null; if (excelApplication != null) { excelApplication.Workbooks.Close(); //Object missing = Type.Missing; excelApplication.Quit(); excelApplication = null; //ReleaseAllRef(excelApplication);//Error } } finally { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } } private void ReleaseAllRef(Object obj) {//ReleaseComObject()方法可使RCW減小一個對COM組件的引用,並返回減小一個引用後RCW對COM組件的剩餘引用數量。 //咱們用一個循環,就可讓RCW將全部對COM組件的引用所有去掉。 try { while (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) > 1) ; } finally { obj = null; } } } }
沒法嵌入互操做類型「Microsoft.Office.Interop.Excel.ApplicationClass」。請改用適用的接口。 winform下對datagridview進行導出時候,寫了一句: Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); 致使結果以下: 類型「Microsoft.Office.Interop.Excel.ApplicationClass」未定義構造函數 沒法嵌入互操做類型「Microsoft.Office.Interop.Excel.ApplicationClass」。請改用適用的接口。 解決辦法是將引用的DLL:Microsoft.Office.Interop.Excel;的嵌入互操做類型改成false,就能夠了。
下載地址:https://files.cnblogs.com/files/emanlee/ExcelLib.rar
轉載連接:http://www.cnblogs.com/emanlee/archive/2007/05/31/766520.html
引用代碼
static void Main(string[] args) { ExcelLib excel = new ExcelLib(); excel.OpenFileName = @"C:\Users\lc\Desktop\test.xlsx"; excel.SaveFileName = @"C:\Users\lc\Desktop\test002.xlsx"; excel.OpenExcelFile(); int columns = excel.getTotalColumnCount(); int rows = excel.getTotalRowCount(); string value = excel.getOneCellValue(1, 1); for (int row = 1; row <= rows; row++) { for (int column = 1; column <= columns; column++) { string xx = excel.getOneCellValue(row, column); Console.WriteLine(xx); } } excel.setOneCellValue(4, 4, "xyz222"); excel.SaveExcel(); }