讓C# Excel導(dǎo)入導(dǎo)出 支持不同版本Office
問題:最近在項(xiàng)目中遇到,不同客戶機(jī)安裝不同Office版本,在導(dǎo)出Excel時(shí),發(fā)生錯(cuò)誤。
找不到Excel Com組件,錯(cuò)誤信息如下。
未能加載文件或程序集“Microsoft.Office.Interop.Excel, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”或它的某一個(gè)依賴項(xiàng)。系統(tǒng)找不到指定的文件。
解決方法:
1.引用高版本的的Excel.dll組件,最新版本14.0.0 防止客戶安裝高版本如Office不能導(dǎo)出。
(DLL組件可以兼容低版本,不能兼容高版本)
2.右鍵DLL屬性,將引用的Excel.dll組件,嵌入互操作類型為True,特定版本=false .這一步非常關(guān)鍵。
嵌入互操作類型 改成True后,生成時(shí)可能現(xiàn)有調(diào)用Excel的代碼會(huì)報(bào)錯(cuò),引用Microsoft.CSharp 命名空間,可以解決此問題。
3.引用Excel 14.0.0 DLL組件方法,vs2012 右鍵添加引用->程序集->擴(kuò)展->Microsoft.Office.Interop.Excel
Excel.dll: http://xiazai.jb51.net/201608/yuanma/Excel(jb51.net).rar
其他方法:
1.使用NPOI.DLL開源組件,可以不安裝Office軟件,進(jìn)行讀寫Excel文件。
NPIO.dll: http://xiazai.jb51.net/201608/yuanma/NPOI(jb51.net).rar
調(diào)用方法如下:
導(dǎo)出代碼:
/// <summary>
/// DataTable導(dǎo)出到Excel的MemoryStream Export()
/// </summary>
/// <param name="dtSource">DataTable數(shù)據(jù)源</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 = "創(chuàng)建程序信息"; //填加xls文件創(chuàng)建程序信息
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
si.Comments = "作者信息"; //填加xls文件作者信息
si.Title = "標(biāo)題信息"; //填加xls文件標(biāo)題信息
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;
//設(shè)置列寬
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
}
#endregion
rowIndex = 2;
}
#endregion
#region 填充內(nèi)容
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"://浮點(diǎn)型
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;
}
}
導(dǎo)入代碼:
/// <summary>
/// 讀取excel ,默認(rèn)第一行為標(biāo)頭
/// </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#發(fā)射方式調(diào)用Excel進(jìn)行,不需要引用Excel.dll組件。此種方法不建議,太麻煩,也需要安裝Office。
調(diào)用方法如下:
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");
}
}
Microsoft.Office.Interop.Excel.Application obj = Activator.CreateInstance(ExcelType) as Microsoft.Office.Interop.Excel.Application;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
欄 目:C#教程
本文標(biāo)題:讓C# Excel導(dǎo)入導(dǎo)出 支持不同版本Office
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6276.html
您可能感興趣的文章
- 01-10C#讀取Excel的三種方式以及比較分析
- 01-10C#定制Excel界面并實(shí)現(xiàn)與數(shù)據(jù)庫(kù)交互的方法
- 01-10C#創(chuàng)建數(shù)據(jù)庫(kù)及導(dǎo)入sql腳本的方法
- 01-10C#實(shí)例代碼之抽獎(jiǎng)升級(jí)版可以經(jīng)表格數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù),抽獎(jiǎng)設(shè)置
- 01-10C#使用Aspose.Cells控件讀取Excel
- 01-10C#實(shí)現(xiàn)Excel動(dòng)態(tài)生成PivotTable
- 01-10C#的Excel導(dǎo)入、導(dǎo)出
- 01-10Winform讓DataGridView左側(cè)顯示圖片
- 01-10C#使用oledb導(dǎo)出數(shù)據(jù)到excel的方法
- 01-10C#.net編程創(chuàng)建Access文件和Excel文件的方法詳解


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過(guò)重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10delphi制作wav文件的方法
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 04-02jquery與jsp,用jquery
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改


