程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 讓C# Excel導入導出,支持不同版本的Office,

讓C# Excel導入導出,支持不同版本的Office,

編輯:C#入門知識

讓C# Excel導入導出,支持不同版本的Office,


問題:最近在項目中遇到,不同客戶機安裝不同Office版本,在導出Excel時,發生錯誤。

找不到Excel Com組件,錯誤信息如下。

未能加載文件或程序集“Microsoft.Office.Interop.Excel, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”或它的某一個依賴項。系統找不到指定的文件。

解決方法:

  1.引用高版本的的Excel.dll組件,最新版本14.0.0 防止客戶安裝高版本如Office不能導出。

  (DLL組件可以兼容低版本,不能兼容高版本)

      2.右鍵DLL屬性,將引用的Excel.dll組件,嵌入互操作類型為True,特定版本=false .這一步非常關鍵。

    嵌入互操作類型 改成True後,生成時可能現有調用Excel的代碼會報錯,引用Microsoft.CSharp 命名空間,可以解決此問題。

      3.引用Excel 14.0.0 DLL組件方法,vs2012 右鍵添加引用->程序集->擴展->Microsoft.Office.Interop.Excel

  Excel.dll     http://files.cnblogs.com/files/ichk/Microsoft.Office.Interop.Excel.rar

      

其他方法:

  1.使用NPOI.DLL開源組件,可以不安裝Office軟件,進行讀寫Excel文件。

  NPIO.dll     http://files.cnblogs.com/files/ichk/NPOI.rar

調用方法如下:

導出代碼:

1 /// <summary> 2 /// DataTable導出到Excel的MemoryStream Export() 3 /// </summary> 4 /// <param name="dtSource">DataTable數據源</param> 5 /// <param name="strHeaderText">Excel表頭文本(例如:車輛列表)</param> 6 public static MemoryStream Export(DataTable dtSource, string strHeaderText) 7 { 8 HSSFWorkbook workbook = new HSSFWorkbook(); 9 ISheet sheet = workbook.CreateSheet(); 10 11 #region 右擊文件 屬性信息 12 { 13 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 14 dsi.Company = "NPOI"; 15 workbook.DocumentSummaryInformation = dsi; 16 17 SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 18 si.Author = "文件作者信息"; //填加xls文件作者信息 19 si.ApplicationName = "創建程序信息"; //填加xls文件創建程序信息 20 si.LastAuthor = "最後保存者信息"; //填加xls文件最後保存者信息 21 si.Comments = "作者信息"; //填加xls文件作者信息 22 si.Title = "標題信息"; //填加xls文件標題信息 23 si.Subject = "主題信息";//填加文件主題信息 24 si.CreateDateTime = System.DateTime.Now; 25 workbook.SummaryInformation = si; 26 } 27 #endregion 28 29 ICellStyle dateStyle = workbook.CreateCellStyle(); 30 IDataFormat format = workbook.CreateDataFormat(); 31 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 32 33 //取得列寬 34 int[] arrColWidth = new int[dtSource.Columns.Count]; 35 foreach (DataColumn item in dtSource.Columns) 36 { 37 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 38 } 39 for (int i = 0; i < dtSource.Rows.Count; i++) 40 { 41 for (int j = 0; j < dtSource.Columns.Count; j++) 42 { 43 int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; 44 if (intTemp > arrColWidth[j]) 45 { 46 arrColWidth[j] = intTemp; 47 } 48 } 49 } 50 int rowIndex = 0; 51 foreach (DataRow row in dtSource.Rows) 52 { 53 #region 新建表,填充表頭,填充列頭,樣式 54 if (rowIndex == 65535 || rowIndex == 0) 55 { 56 if (rowIndex != 0) 57 { 58 sheet = workbook.CreateSheet(); 59 } 60 61 #region 表頭及樣式 62 { 63 IRow headerRow = sheet.CreateRow(0); 64 headerRow.HeightInPoints = 25; 65 headerRow.CreateCell(0).SetCellValue(strHeaderText); 66 67 ICellStyle headStyle = workbook.CreateCellStyle(); 68 headStyle.Alignment = HorizontalAlignment.CENTER; 69 IFont font = workbook.CreateFont(); 70 font.FontHeightInPoints = 20; 71 font.Boldweight = 700; 72 headStyle.SetFont(font); 73 headerRow.GetCell(0).CellStyle = headStyle; 74 sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); 75 } 76 #endregion 77 78 #region 列頭及樣式 79 { 80 IRow headerRow = sheet.CreateRow(1); 81 ICellStyle headStyle = workbook.CreateCellStyle(); 82 headStyle.Alignment = HorizontalAlignment.CENTER; 83 IFont font = workbook.CreateFont(); 84 font.FontHeightInPoints = 10; 85 font.Boldweight = 700; 86 headStyle.SetFont(font); 87 foreach (DataColumn column in dtSource.Columns) 88 { 89 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 90 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 91 92 //設置列寬 93 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 94 } 95 } 96 #endregion 97 98 rowIndex = 2; 99 } 100 #endregion 101 102 #region 填充內容 103 IRow dataRow = sheet.CreateRow(rowIndex); 104 foreach (DataColumn column in dtSource.Columns) 105 { 106 ICell newCell = dataRow.CreateCell(column.Ordinal); 107 108 string drValue = row[column].ToString(); 109 110 switch (column.DataType.ToString()) 111 { 112 case "System.String"://字符串類型 113 newCell.SetCellValue(drValue); 114 break; 115 case "System.DateTime"://日期類型 116 System.DateTime dateV; 117 System.DateTime.TryParse(drValue, out dateV); 118 newCell.SetCellValue(dateV); 119 120 newCell.CellStyle = dateStyle;//格式化顯示 121 break; 122 case "System.Boolean"://布爾型 123 bool boolV = false; 124 bool.TryParse(drValue, out boolV); 125 newCell.SetCellValue(boolV); 126 break; 127 case "System.Int16"://整型 128 case "System.Int32": 129 case "System.Int64": 130 case "System.Byte": 131 int intV = 0; 132 int.TryParse(drValue, out intV); 133 newCell.SetCellValue(intV); 134 break; 135 case "System.Decimal"://浮點型 136 case "System.Double": 137 double doubV = 0; 138 double.TryParse(drValue, out doubV); 139 newCell.SetCellValue(doubV); 140 break; 141 case "System.DBNull"://空值處理 142 newCell.SetCellValue(""); 143 break; 144 default: 145 newCell.SetCellValue(""); 146 break; 147 } 148 } 149 #endregion 150 151 rowIndex++; 152 } 153 using (MemoryStream ms = new MemoryStream()) 154 { 155 workbook.Write(ms); 156 ms.Flush(); 157 ms.Position = 0; 158 sheet.Dispose(); 159 return ms; 160 } 161 } View Code

 

導入代碼:

1 /// <summary> 2 /// 讀取excel ,默認第一行為標頭 3 /// </summary> 4 /// <param name="strFileName">excel文檔路徑</param> 5 /// <returns></returns> 6 public static DataTable Import(string strFileName) 7 { 8 DataTable dt = new DataTable(); 9 10 HSSFWorkbook hssfworkbook; 11 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 12 { 13 hssfworkbook = new HSSFWorkbook(file); 14 } 15 ISheet sheet = hssfworkbook.GetSheetAt(0); 16 System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); 17 18 IRow headerRow = sheet.GetRow(0); 19 int cellCount = headerRow.LastCellNum; 20 21 for (int j = 0; j < cellCount; j++) 22 { 23 ICell cell = headerRow.GetCell(j); 24 dt.Columns.Add(cell.ToString()); 25 } 26 27 for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) 28 { 29 IRow row = sheet.GetRow(i); 30 DataRow dataRow = dt.NewRow(); 31 32 for (int j = row.FirstCellNum; j < cellCount; j++) 33 { 34 if (row.GetCell(j) != null) 35 dataRow[j] = row.GetCell(j).ToString(); 36 } 37 38 dt.Rows.Add(dataRow); 39 } 40 return dt; 41 } View Code

 

      2.使用C#發射方式調用Excel進行,不需要引用Excel.dll組件。此種方法不建議,太麻煩,也需要安裝Office。

      調用方法如下:

  

1 private void Export2Excel(DataGridView datagridview, bool captions) 2 { 3 object objApp_Late; 4 object objBook_Late; 5 object objBooks_Late; 6 object objSheets_Late; 7 object objSheet_Late; 8 object objRange_Late; 9 object[] Parameters; 10 11 string[] headers = new string[datagridview.DisplayedColumnCount(true)]; 12 string[] columns = new string[datagridview.DisplayedColumnCount(true)]; 13 string[] colName = new string[datagridview.DisplayedColumnCount(true)]; 14 15 int i = 0; 16 int c = 0; 17 int m = 0; 18 19 for (c = 0; c < datagridview.Columns.Count; c++) 20 { 21 for (int j = 0; j < datagridview.Columns.Count; j++) 22 { 23 DataGridViewColumn tmpcol = datagridview.Columns[j]; 24 if (tmpcol.DisplayIndex == c) 25 { 26 if (tmpcol.Visible) //不顯示的隱藏列初始化為tag=0 27 { 28 headers[c - m] = tmpcol.HeaderText; 29 i = c - m + 65; 30 columns[c - m] = Convert.ToString((char)i); 31 colName[c - m] = tmpcol.Name; 32 } 33 else 34 { 35 m++; 36 } 37 break; 38 } 39 } 40 } 41 42 try 43 { 44 // Get the class type and instantiate Excel. 45 Type objClassType; 46 objClassType = Type.GetTypeFromProgID("Excel.Application"); 47 objApp_Late = Activator.CreateInstance(objClassType); 48 //Get the workbooks collection. 49 objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, objApp_Late, null); 50 //Add a new workbook. 51 objBook_Late = objBooks_Late.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, objBooks_Late, null); 52 //Get the worksheets collection. 53 objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, objBook_Late, null); 54 //Get the first worksheet. 55 Parameters = new Object[1]; 56 Parameters[0] = 1; 57 objSheet_Late = objSheets_Late.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, objSheets_Late, Parameters); 58 59 if (captions) 60 { 61 // Create the headers in the first row of the sheet 62 for (c = 0; c < datagridview.DisplayedColumnCount(true); c++) 63 { 64 //Get a range object that contains cell. 65 Parameters = new Object[2]; 66 Parameters[0] = columns[c] + "1"; 67 Parameters[1] = Missing.Value; 68 objRange_Late = objSheet_Late.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, objSheet_Late, Parameters); 69 //Write Headers in cell. 70 Parameters = new Object[1]; 71 Parameters[0] = headers[c]; 72 objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objRange_Late, Parameters); 73 } 74 } 75 76 // Now add the data from the grid to the sheet starting in row 2 77 for (i = 0; i < datagridview.RowCount; i++) 78 { 79 c = 0; 80 foreach (string txtCol in colName) 81 { 82 DataGridViewColumn col = datagridview.Columns[txtCol]; 83 if (col.Visible) 84 { 85 //Get a range object that contains cell. 86 Parameters = new Object[2]; 87 Parameters[0] = columns[c] + Convert.ToString(i + 2); 88 Parameters[1] = Missing.Value; 89 objRange_Late = objSheet_Late.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, objSheet_Late, Parameters); 90 //Write Headers in cell. 91 Parameters = new Object[1]; 92 //Parameters[0] = datagridview.Rows[i].Cells[headers[c]].Value.ToString(); 93 Parameters[0] = datagridview.Rows[i].Cells[col.Name].Value.ToString(); 94 objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objRange_Late, Parameters); 95 c++; 96 } 97 98 } 99 } 100 101 //Return control of Excel to the user. 102 Parameters = new Object[1]; 103 Parameters[0] = true; 104 objApp_Late.GetType().InvokeMember("Visible", BindingFlags.SetProperty, 105 null, objApp_Late, Parameters); 106 objApp_Late.GetType().InvokeMember("UserControl", BindingFlags.SetProperty, 107 null, objApp_Late, Parameters); 108 } 109 catch (Exception theException) 110 { 111 String errorMessage; 112 errorMessage = "Error: "; 113 errorMessage = String.Concat(errorMessage, theException.Message); 114 errorMessage = String.Concat(errorMessage, " Line: "); 115 errorMessage = String.Concat(errorMessage, theException.Source); 116 117 MessageBox.Show(errorMessage, "Error"); 118 } 119 } View Code 導出

 

System.Type ExcelType = System.Type.GetTypeFromProgID("Excel.Application");
Microsoft.Office.Interop.Excel.Application obj = Activator.CreateInstance(ExcelType) as Microsoft.Office.Interop.Excel.Application;

 

  

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved