




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第C#使用NPOI將List數(shù)據(jù)導(dǎo)出到Excel文檔NPOI是一個(gè)開(kāi)源的C#讀寫(xiě)Excel、WORD等微軟OLE2組件文檔的項(xiàng)目。使用NPOI可以在沒(méi)有安裝Office或者相應(yīng)環(huán)境的機(jī)器上對(duì)WORD/EXCEL文檔進(jìn)行讀寫(xiě)。
這里簡(jiǎn)單封裝了一個(gè)使用NPOI導(dǎo)出Excel的DLL,方便項(xiàng)目使用。步驟如下:
1、NuGet包管理器添加對(duì)NPOI和log4net的安裝引用
2、添加Excel屬性信息類(lèi)ExcelProperty.cs
///summary
///用于定義導(dǎo)出的excel屬性
////summary
publicclassExcelProperty
{
publicExcelProperty(){}
///summary
///文件基本屬性
////summary
///paramname="company"公司名稱(chēng)/param
///paramname="author"作者信息/param
///paramname="ApplicationName"創(chuàng)建程序信息/param
///paramname="Comments"填加xls文件備注/param
///paramname="title"填加xls文件標(biāo)題信息/param
///paramname="Subject"填加文件主題信息/param
publicExcelProperty(stringcompany,stringauthor,stringapplicationName,stringcomments,stringtitle,stringsubject)
{
this.Company=company;
this.Author=author;
this.ApplicationName=applicationName;
this.Comments=comments;
this.Title=title;
this.Subject=subject;
}
///summary
///公司名稱(chēng)
////summary
privatestringcompany="";
///summary
///公司名稱(chēng)
////summary
publicstringCompany
{
get{returncompany;}
set{company=value;}
}
///summary
///作者信息
////summary
privatestringauthor="";
///summary
///作者信息
////summary
publicstringAuthor
{
get{returnauthor;}
set{author=value;}
}
///summary
///創(chuàng)建程序信息
////summary
privatestringapplicationName="";
///summary
///創(chuàng)建程序信息
////summary
publicstringApplicationName
{
get{returnapplicationName;}
set{applicationName=value;}
}
///summary
///填加xls文件備注
////summary
privatestringcomments="";
///summary
///填加xls文件備注
////summary
publicstringComments
{
get{returncomments;}
set{comments=value;}
}
///summary
///填加xls文件標(biāo)題信息
////summary
privatestringtitle="";
///summary
///填加xls文件標(biāo)題信息
////summary
publicstringTitle
{
get{returntitle;}
set{title=value;}
}
///summary
///填加文件主題信息
////summary
privatestringsubject="";
///summary
///填加文件主題信息
////summary
publicstringSubject
{
get{returnsubject;}
set{subject=value;}
}
}
3、添加Excel導(dǎo)出類(lèi)ExcelExportHelper.cs
usinglog4net;
usingNPOI.HPSF;
usingNPOI.HSSF.UserModel;
usingNPOI.SS.UserModel;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Data;
usingSystem.IO;
usingSystem.Reflection;
usingSystem.Text;
namespaceNPOIExcelExportHelper
publicclassExcelExportHelper
{
//委托
publicdelegatevoidExportResult(boolres);
publiceventExportResultExportResultEvent;
//構(gòu)造函數(shù)
publicExcelExportHelper(){}
publicExcelExportHelper(ILogloghelper)
{
this.LogHelper=loghelper;
}
///summary
///日志
////summary
privateILogLogHelper;
///summary
///要導(dǎo)出的Excel對(duì)象
////summary
privateHSSFWorkbookworkbook=null;
///summary
///要導(dǎo)出的Excel對(duì)象屬性
////summary
privateHSSFWorkbookWorkbook
{
get
{
if(workbook==null)
{
workbook=newHSSFWorkbook();
}
returnworkbook;
}
set{workbook=value;}
}
///summary
///設(shè)置Excel文件基本屬性
////summary
///paramname="ep"屬性/param
publicvoidSetExcelProperty(ExcelPropertyep)
{
DocumentSummaryInformationdsi=PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company=ep.Company;//填加xls文件公司信息
Workbook.DocumentSummaryInformation=dsi;
SummaryInformationsi=PropertySetFactory.CreateSummaryInformation();
si.Author=ep.Author;//填加xls文件作者信息
si.ApplicationName=ep.ApplicationName;//填加xls文件創(chuàng)建程序信息
si.Comments=ep.Comments;//填加xls文件備注
si.Title=ep.Title;//填加xls文件標(biāo)題信息
si.Subject=ep.Subject;//填加文件主題信息
si.CreateDateTime=DateTime.Now;
Workbook.SummaryInformation=si;
}
///summary
///泛型列表List導(dǎo)出到Excel文件
////summary
///paramname="list"源List表/param
///paramname="strHeaderText"標(biāo)題信息/param
///paramname="strFileName"保存路徑/param
///paramname="titles"列名/param
publicvoidExportToFileT(ListTlist,stringstrHeaderText,stringstrFileName,string[]titles=null)
{
try
{
//轉(zhuǎn)換數(shù)據(jù)源
DataTabledtSource=ListToDataTable(list,titles);
//開(kāi)始導(dǎo)出
Export(dtSource,strHeaderText,strFileName);
System.GC.Collect();
ExportResultEvent.Invoke(true);
}
catch(Exceptionex)
{
if(LogHelper!=null)
LogHelper.Error(string.Format("ExportToFileerror:{0}",ex));
ExportResultEvent.Invoke(false);
}
}
///summary
///DataTable導(dǎo)出到Excel文件
////summary
///paramname="dtSource"源DataTable/param
///paramname="strHeaderText"標(biāo)題信息/param
///paramname="strFileName"保存路徑/param
publicvoidExport(DataTabledtSource,stringstrHeaderText,stringstrFileName)
{
using(MemoryStreamms=Export(dtSource,strHeaderText))
{
using(FileStreamfs=newFileStream(strFileName,FileMode.Create,FileAccess.Write))
{
byte[]data=ms.ToArray();
fs.Write(data,0,data.Length);
fs.Flush();
}
}
}
///summary
///DataTable導(dǎo)出到Excel的MemoryStream
////summary
///paramname="dtSource"源DataTable/param
///paramname="strHeaderText"標(biāo)題信息/param
privateMemoryStreamExport(DataTabledtSource,stringstrHeaderText)
{
ISheetsheet=Workbook.CreateSheet();
ICellStyledateStyle=Workbook.CreateCellStyle();
IDataFormatformat=Workbook.CreateDataFormat();
dateStyle.DataFormat=format.GetFormat("yyyy-mm-dd");
//取得列寬
int[]arrColWidth=newint[dtSource.Columns.Count];
foreach(DataColumnitemindtSource.Columns)
{
arrColWidth[item.Ordinal]=Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
}
for(inti=0;idtSource.Rows.Count;i++)
{
for(intj=0;jdtSource.Columns.Count;j++)
{
intintTemp=Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if(intTemparrColWidth[j])
{
arrColWidth[j]=intTemp;
}
}
}
introwIndex=0;
foreach(DataRowrowindtSource.Rows)
{
#region新建表,填充表頭,填充列頭,樣式
if(rowIndex==65535||rowIndex==0)
{
if(rowIndex!=0)
{
sheet=Workbook.CreateSheet();
}
#region表頭及樣式
{
IRowheaderRow=sheet.CreateRow(0);
headerRow.HeightInPoints=25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
ICellStyleheadStyle=Workbook.CreateCellStyle();
headStyle.Alignment=HorizontalAlignment.Center;
IFontfont=Workbook.CreateFont();
font.FontHeightInPoints=20;
font.Boldweight=700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle=headStyle;
//CellRangeAddress四個(gè)參數(shù)為:起始行,結(jié)束行,起始列,結(jié)束列
sheet.AddMergedRegion(newNPOI.SS.Util.CellRangeAddress(0,0,0,dtSource.Columns.Count-1));
}
#endregion
#region列頭及樣式
{
IRowheaderRow=sheet.CreateRow(1);
ICellStyleheadStyle=Workbook.CreateCellStyle();
headStyle.Alignment=HorizontalAlignment.Center;
IFontfont=Workbook.CreateFont();
font.FontHeightInPoints=10;
font.Boldweight=700;
headStyle.SetFont(font);
foreach(DataColumncolumnindtSource.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)容
IRowdataRow=sheet.CreateRow(rowIndex);
foreach(DataColumncolumnindtSource.Columns)
{
ICellnewCell=dataRow.CreateCell(column.Ordinal);
stringdrValue=row[column].ToString();
switch(column.DataType.ToString())
{
case"System.String"://字符串類(lèi)型
newCell.SetCellValue(drValue);
break;
case"System.DateTime"://日期類(lèi)型
DateTimedateV;
DateTime.TryParse(drValue,outdateV);
newCell.SetCellValue(dateV);
newCell.CellStyle=dateStyle;//格式化顯示
break;
case"System.Boolean"://布爾型
boolboolV=false;
bool.TryParse(drValue,outboolV);
newCell.SetCellValue(boolV);
break;
case"System.Int16"://整型
case"System.Int32":
case"System.Int64":
case"System.Byte":
intintV=0;
int.TryParse(drValue,outintV);
newCell.SetCellValue(intV);
break;
case"System.Decimal"://浮點(diǎn)型
case"System.Double":
doubledoubV=0;
double.TryParse(drValue,outdoubV);
newCell.SetCellValue(doubV);
break;
case"System.DBNull"://空值處理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
#endregion
rowIndex++;
}
using(MemoryStreamms=newMemoryStream())
{
Workbook.Write(ms);
ms.Flush();
ms.Position=0;
returnms;
}
}
///summary
///泛型列表List轉(zhuǎn)換為DataTable
////summary
///typeparamname="T"泛型實(shí)體/typeparam
///paramname="list"要轉(zhuǎn)換的列表/param
///paramname="titles"標(biāo)題/param
///returns/returns
publicDataTableListToDataTableT(ListTlist,string[]titles)
{
DataTabledt=newDataTable();
TypelistType=typeof(T);
PropertyInfo[]properties=listType.GetProperties();
//標(biāo)題行
if(titles!=nullproperties.Length==titles.Length)
{
for(inti=0;iproperties.Length;i++)
{
PropertyInfoproperty=properties[i];
dt.Columns.Add(newDataColumn(titles[i],property.PropertyType));
}
}
else
{
for(inti=0;iproperties.Length;i++)
{
PropertyInfoproperty=properties[i];
dt.Columns.Add(newDataColumn(property.Name,property.PropertyType));
}
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 環(huán)保循環(huán)活動(dòng)方案
- 愛(ài)國(guó)實(shí)踐活動(dòng)方案
- 生命教育月活動(dòng)方案
- 特長(zhǎng)天天練活動(dòng)方案
- 焦點(diǎn)解決團(tuán)輔活動(dòng)方案
- 環(huán)游中國(guó)活動(dòng)方案
- 愛(ài)護(hù)牙齒項(xiàng)目活動(dòng)方案
- 愛(ài)情校園活動(dòng)策劃方案
- 理性消費(fèi)校園活動(dòng)方案
- 物理渠道體驗(yàn)活動(dòng)方案
- 2024中國(guó)醫(yī)藥行業(yè)人才發(fā)展報(bào)告-智聯(lián)招聘-202404
- 《安全生產(chǎn)課件-氧化鋁粉塵隱患與控制》
- 汽輪機(jī)檢修安全施工方案
- 2024年課外閱讀《中國(guó)古代寓言故事》知識(shí)考試題與答案
- DB32/T 4699-2024 企業(yè)應(yīng)急能力評(píng)估規(guī)范
- MATLAB運(yùn)用simulink建立簡(jiǎn)單的單機(jī)無(wú)窮大系統(tǒng)仿真模擬數(shù)字電子技術(shù)
- 2024屆貴州省貴陽(yáng)市普通高中化學(xué)高二下期末學(xué)業(yè)水平測(cè)試模擬試題含解析
- 心理輔導(dǎo)室配置清單及預(yù)算
- GB/T 23101.3-2023外科植入物羥基磷灰石第3部分:結(jié)晶度和相純度的化學(xué)分析和表征
- 石英晶體諧振器培訓(xùn)資料
- 紫羅蘭永恒花園
評(píng)論
0/150
提交評(píng)論