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

讓C# Excel導入導出 支撐分歧版本Office

編輯:C#入門知識

讓C# Excel導入導出 支撐分歧版本Office。本站提示廣大學習愛好者:(讓C# Excel導入導出 支撐分歧版本Office)文章只能為提供參考,不一定能成為您想要的結果。以下是讓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://xiazai.jb51.net/201608/yuanma/Excel(jb51.net).rar

其他辦法:
1.應用NPOI.DLL開源組件,可以不裝置Office軟件,停止讀寫Excel文件。
NPIO.dll:  http://xiazai.jb51.net/201608/yuanma/NPOI(jb51.net).rar

挪用辦法以下: 

導出代碼:

/// <summary>
 /// DataTable導出到Excel的MemoryStream Export()
 /// </summary>
 /// <param name="dtSource">DataTable數據源</param>
 /// <param name="strHeaderText">Excel表頭文本(例如:車輛列表)</param>
 public static MemoryStream Export(DataTable dtSource, string strHeaderText)
 {
 HSSFWorkbook workbook = new HSSFWorkbook();
 ISheet sheet = workbook.CreateSheet();
 
 #region 右擊文件 屬性信息
 {
  DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  dsi.Company = "NPOI";
  workbook.DocumentSummaryInformation = dsi;

  SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  si.Author = "文件作者信息"; //填加xls文件作者信息
  si.ApplicationName = "創立法式信息"; //填加xls文件創立法式信息
  si.LastAuthor = "最初保留者信息"; //填加xls文件最初保留者信息
  si.Comments = "作者信息"; //填加xls文件作者信息
  si.Title = "題目信息"; //填加xls文件題目信息
  si.Subject = "主題信息";//填加文件主題信息
  si.CreateDateTime = System.DateTime.Now;
  workbook.SummaryInformation = si;
 }
 #endregion

 ICellStyle dateStyle = workbook.CreateCellStyle();
 IDataFormat format = workbook.CreateDataFormat();
 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
 
 //獲得列寬
 int[] arrColWidth = new int[dtSource.Columns.Count];
 foreach (DataColumn item in dtSource.Columns)
 {
  arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
 }
 for (int i = 0; i < dtSource.Rows.Count; i++)
 {
  for (int j = 0; j < dtSource.Columns.Count; j++)
  {
  int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  if (intTemp > arrColWidth[j])
  {
   arrColWidth[j] = intTemp;
  }
  }
 }
 int rowIndex = 0;
 foreach (DataRow row in dtSource.Rows)
 {
  #region 新建表,填充表頭,填充列頭,款式
  if (rowIndex == 65535 || rowIndex == 0)
  {
  if (rowIndex != 0)
  {
   sheet = workbook.CreateSheet();
  }

  #region 表頭及款式
  {
   IRow headerRow = sheet.CreateRow(0);
   headerRow.HeightInPoints = 25;
   headerRow.CreateCell(0).SetCellValue(strHeaderText);

   ICellStyle headStyle = workbook.CreateCellStyle();
   headStyle.Alignment = HorizontalAlignment.CENTER; 
   IFont font = workbook.CreateFont();
   font.FontHeightInPoints = 20;
   font.Boldweight = 700;
   headStyle.SetFont(font);
   headerRow.GetCell(0).CellStyle = headStyle;
   sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); 
  }
  #endregion

  #region 列頭及款式
  {
   IRow headerRow = sheet.CreateRow(1);
   ICellStyle headStyle = workbook.CreateCellStyle();
   headStyle.Alignment = HorizontalAlignment.CENTER; 
   IFont font = workbook.CreateFont();
   font.FontHeightInPoints = 10;
   font.Boldweight = 700;
   headStyle.SetFont(font);
   foreach (DataColumn column in dtSource.Columns)
   {
   headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
   headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

   //設置列寬
   sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
   }
  }
  #endregion

  rowIndex = 2;
  }
  #endregion

  #region 填充內容
  IRow dataRow = sheet.CreateRow(rowIndex);
  foreach (DataColumn column in dtSource.Columns)
  {
  ICell newCell = dataRow.CreateCell(column.Ordinal);

  string drValue = row[column].ToString();

  switch (column.DataType.ToString())
  {
   case "System.String"://字符串類型
   newCell.SetCellValue(drValue);
   break;
   case "System.DateTime"://日期類型
   System.DateTime dateV;
   System.DateTime.TryParse(drValue, out dateV);
   newCell.SetCellValue(dateV);

   newCell.CellStyle = dateStyle;//格局化顯示
   break;
   case "System.Boolean"://布爾型
   bool boolV = false;
   bool.TryParse(drValue, out boolV);
   newCell.SetCellValue(boolV);
   break;
   case "System.Int16"://整型
   case "System.Int32":
   case "System.Int64":
   case "System.Byte":
   int intV = 0;
   int.TryParse(drValue, out intV);
   newCell.SetCellValue(intV);
   break;
   case "System.Decimal"://浮點型
   case "System.Double":
   double doubV = 0;
   double.TryParse(drValue, out doubV);
   newCell.SetCellValue(doubV);
   break;
   case "System.DBNull"://空值處置
   newCell.SetCellValue("");
   break;
   default:
   newCell.SetCellValue("");
   break;
  }
  }
  #endregion

  rowIndex++;
 }
 using (MemoryStream ms = new MemoryStream())
 {
  workbook.Write(ms);
  ms.Flush();
  ms.Position = 0;
  sheet.Dispose();
  return ms;
 }
 }

導入代碼:

/// <summary>
 /// 讀取excel ,默許第一行動標頭
 /// </summary>
 /// <param name="strFileName">excel文檔途徑</param>
 /// <returns></returns>
 public static DataTable Import(string strFileName)
 {
 DataTable dt = new DataTable();

 HSSFWorkbook hssfworkbook;
 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
 {
  hssfworkbook = new HSSFWorkbook(file);
 }
 ISheet sheet = hssfworkbook.GetSheetAt(0);
 System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

 IRow headerRow = sheet.GetRow(0);
 int cellCount = headerRow.LastCellNum;

 for (int j = 0; j < cellCount; j++)
 {
  ICell cell = headerRow.GetCell(j);
  dt.Columns.Add(cell.ToString());
 }

 for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
 {
  IRow row = sheet.GetRow(i);
  DataRow dataRow = dt.NewRow();

  for (int j = row.FirstCellNum; j < cellCount; j++)
  {
  if (row.GetCell(j) != null)
   dataRow[j] = row.GetCell(j).ToString();
  }

  dt.Rows.Add(dataRow);
 }
 return dt;
 }

2.應用C#發射方法挪用Excel停止,不須要援用Excel.dll組件。此種辦法不建議,太費事,也須要裝置Office。
挪用辦法以下:

private void Export2Excel(DataGridView datagridview, bool captions)
 {
  object objApp_Late;
  object objBook_Late;
  object objBooks_Late;
  object objSheets_Late;
  object objSheet_Late;
  object objRange_Late;
  object[] Parameters;

  string[] headers = new string[datagridview.DisplayedColumnCount(true)];
  string[] columns = new string[datagridview.DisplayedColumnCount(true)];
  string[] colName = new string[datagridview.DisplayedColumnCount(true)];

  int i = 0;
  int c = 0;
  int m = 0;

  for (c = 0; c < datagridview.Columns.Count; c++)
  {
  for (int j = 0; j < datagridview.Columns.Count; j++)
  {
   DataGridViewColumn tmpcol = datagridview.Columns[j];
   if (tmpcol.DisplayIndex == c)
   {
   if (tmpcol.Visible) //不顯示的隱蔽列初始化為tag=0
   {
    headers[c - m] = tmpcol.HeaderText;
    i = c - m + 65;
    columns[c - m] = Convert.ToString((char)i);
    colName[c - m] = tmpcol.Name;
   }
   else
   {
    m++;
   }
   break;
   }
  }
  }

  try
  {
  // Get the class type and instantiate Excel.
  Type objClassType;
  objClassType = Type.GetTypeFromProgID("Excel.Application");
  objApp_Late = Activator.CreateInstance(objClassType);
  //Get the workbooks collection.
  objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, objApp_Late, null);
  //Add a new workbook.
  objBook_Late = objBooks_Late.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, objBooks_Late, null);
  //Get the worksheets collection.
  objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, objBook_Late, null);
  //Get the first worksheet.
  Parameters = new Object[1];
  Parameters[0] = 1;
  objSheet_Late = objSheets_Late.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, objSheets_Late, Parameters);

  if (captions)
  {
   // Create the headers in the first row of the sheet
   for (c = 0; c < datagridview.DisplayedColumnCount(true); c++)
   {
   //Get a range object that contains cell.
   Parameters = new Object[2];
   Parameters[0] = columns[c] + "1";
   Parameters[1] = Missing.Value;
   objRange_Late = objSheet_Late.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, objSheet_Late, Parameters);
   //Write Headers in cell.
   Parameters = new Object[1];
   Parameters[0] = headers[c];
   objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objRange_Late, Parameters);
   }
  }

  // Now add the data from the grid to the sheet starting in row 2
  for (i = 0; i < datagridview.RowCount; i++)
  {
   c = 0;
   foreach (string txtCol in colName)
   {
   DataGridViewColumn col = datagridview.Columns[txtCol];
   if (col.Visible)
   {
    //Get a range object that contains cell.
    Parameters = new Object[2];
    Parameters[0] = columns[c] + Convert.ToString(i + 2);
    Parameters[1] = Missing.Value;
    objRange_Late = objSheet_Late.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, objSheet_Late, Parameters);
    //Write Headers in cell.
    Parameters = new Object[1];
    //Parameters[0] = datagridview.Rows[i].Cells[headers[c]].Value.ToString();
    Parameters[0] = datagridview.Rows[i].Cells[col.Name].Value.ToString();
    objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objRange_Late, Parameters);
    c++;
   }

   }
  }

  //Return control of Excel to the user.
  Parameters = new Object[1];
  Parameters[0] = true;
  objApp_Late.GetType().InvokeMember("Visible", BindingFlags.SetProperty,
  null, objApp_Late, Parameters);
  objApp_Late.GetType().InvokeMember("UserControl", BindingFlags.SetProperty,
  null, objApp_Late, Parameters);
  }
  catch (Exception theException)
  {
  String errorMessage;
  errorMessage = "Error: ";
  errorMessage = String.Concat(errorMessage, theException.Message);
  errorMessage = String.Concat(errorMessage, " Line: ");
  errorMessage = String.Concat(errorMessage, theException.Source);

  MessageBox.Show(errorMessage, "Error");
  }
 }


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