




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第基于NPOI用C#開(kāi)發(fā)的Excel以及表格設(shè)置本文為大家分享了基于NPOI用C#開(kāi)發(fā)的Excel以及表格設(shè)置,供大家參考,具體內(nèi)容如下
最近在項(xiàng)目中需要導(dǎo)出Excel。在這里做個(gè)記錄。在網(wǎng)上查閱了一些資料。將自己最終的代碼分享在這里,以供自己日后查閱,如果能給陌生的你帶來(lái)方便,那便更好。
開(kāi)發(fā)的過(guò)程中也遇到了一個(gè)問(wèn)題,設(shè)置字體會(huì)導(dǎo)致打開(kāi)Excel時(shí)報(bào)錯(cuò)(錯(cuò)誤:此文件中的某些文本格式可能已經(jīng)更改,因?yàn)樗呀?jīng)超出最多允許的字體數(shù)),并且設(shè)置失敗。這個(gè)問(wèn)題產(chǎn)生的原因是因?yàn)轭l繁的創(chuàng)建字體,這個(gè)在我參考的代碼中是有問(wèn)題,我做了些改善。如果你有更優(yōu)的方案,期待向你學(xué)習(xí)。
publicclassExcelDAL
{
#region定義單元格常用到樣式的枚舉
publicenumstylexls
{
頭,
列標(biāo)題,
url,
時(shí)間,
數(shù)字,
錢,
百分比,
中文大寫(xiě),
科學(xué)計(jì)數(shù)法,
默認(rèn)
}
#endregion
//定義工作薄
privatestaticIWorkbookm_workbook;
//定義sheet表
privatestaticISheetm_sheet;
//表名
privatestaticListstringm_sheets=newListstring
privatestaticICellStylem_cellStyle;
privatestaticIDataFormatm_datastyle;
//字體
privatestaticIFontm_font20;
//字體
privatestaticIFontm_font12;
//字體
privatestaticIFontm_font;
///summary
///創(chuàng)建Excel表
////summary
///paramname="dt"傳遞datatable數(shù)據(jù)類型/param
///paramname="filePath"文件保存路徑/param
///paramname="sheetName"工作表名/param
///paramname="headerName"表格標(biāo)題名/param
///returns/returns
publicstaticboolExportExcel(System.Data.DataTabledt,stringfilePath,stringsheetName,stringheaderName="考勤表")
{
ICellStylecellstytle=null;
try
{
//如果Excel存在就獲取IWorkbook對(duì)象,否則就重新創(chuàng)建
if(File.Exists(filePath))
{
FileStreamfs=newFileStream(filePath,FileMode.Open,FileAccess.Read);
if(filePath.IndexOf(".xlsx")0)//2007版本
m_workbook=newXSSFWorkbook(fs);
elseif(filePath.IndexOf(".xls")0)//2003版本
m_workbook=newHSSFWorkbook(fs);
}
else
{
//創(chuàng)建一個(gè)工作簿
m_workbook=newHSSFWorkbook();
}
if(m_workbook!=null)
{
//獲取所有SheetName
intcount=m_workbook.NumberOfSheets;
//如果該工作簿不存在表就創(chuàng)建新表
if(count1)
{
//創(chuàng)建一個(gè)sheet表
m_sheet=m_workbook.CreateSheet(sheetName);
}
else
{
m_sheets.Clear();
for(inti=0;icount;i++)
{
m_sheet=m_workbook.GetSheetAt(i);
m_sheets.Add(m_sheet.SheetName);
}
if(m_sheets.Contains(sheetName))
{
m_sheet=m_workbook.CreateSheet(sheetName+System.DateTime.Now.ToString("HH-mm-ss")+"副本");
}
else
{
m_sheet=m_workbook.CreateSheet(sheetName);
}
}
}
else
{
returnfalse;
}
#region打印設(shè)置
m_sheet.PrintSetup.Copies=3;
m_sheet.PrintSetup.Landscape=false;
m_sheet.PrintSetup.Scale=100;
//紙張?jiān)O(shè)置,A4紙
m_sheet.PrintSetup.PaperSize=9;
//打印網(wǎng)格線
m_sheet.IsPrintGridlines=true;
#endregion
#region設(shè)置表頭
m_sheet.AddMergedRegion(newNPOI.SS.Util.CellRangeAddress(0,0,0,dt.Columns.Count-1));//合并單元格
IRowrow0=m_sheet.CreateRow(0);
//創(chuàng)建一行
row0.Height=50*20;
ICellicelltop0=row0.CreateCell(0);
//創(chuàng)建一個(gè)單元格
IFontfont=m_workbook.CreateFont();
font.FontHeightInPoints=30;
icelltop0.CellStyle=Getcellstyle(m_workbook,stylexls.頭);
icelltop0.SetCellValue(headerName);
#endregion
#region設(shè)置列
IRowrowH=m_sheet.CreateRow(1);
cellstytle=Getcellstyle(m_workbook,stylexls.列標(biāo)題);
//設(shè)置列名
foreach(DataColumncolindt.Columns)
{
//創(chuàng)建單元格并設(shè)置單元格內(nèi)容
rowH.CreateCell(col.Ordinal).SetCellValue(col.Caption);
//設(shè)置單元格格式
rowH.Cells[col.Ordinal].CellStyle=cellstytle;
}
#endregion
//寫(xiě)入數(shù)據(jù)
cellstytle=Getcellstyle(m_workbook,stylexls.默認(rèn));
for(inti=0;idt.Rows.Count;i++)
{
//跳過(guò)前兩行,第一行為標(biāo)題,第二行為列名
IRowrow=m_sheet.CreateRow(i+2);
ICellcell=row.CreateCell(0);
for(intj=0;jdt.Columns.Count;j++)
{
cell=row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
cell.CellStyle=cellstytle;
}
}
//獲取當(dāng)前列的寬度,然后對(duì)比本列的長(zhǎng)度,取最大值
for(intcolumnNum=0;columnNum=dt.Rows.Count;columnNum++)
{
intcolumnWidth=m_sheet.GetColumnWidth(columnNum)/256;
for(introwNum=1;rowNum=m_sheet.LastRowNum;rowNum++)
{
IRowcurrentRow;
//當(dāng)前行未被使用過(guò)
if(m_sheet.GetRow(rowNum)==null)
{
currentRow=m_sheet.CreateRow(rowNum);
}
else
{
currentRow=m_sheet.GetRow(rowNum);
}
if(currentRow.GetCell(columnNum)!=null)
{
ICellcurrentCell=currentRow.GetCell(columnNum);
intlength=Encoding.Default.GetBytes(currentCell.ToString()).Length;
if(columnWidthlength)
{
columnWidth=length+10;
}
}
}
m_sheet.SetColumnWidth(columnNum,columnWidth*256);
//m_sheet.SetColumnWidth(0,30*256);
//m_sheet.SetColumnWidth(1,10*256);
//m_sheet.SetColumnWidth(2,25*256);
//m_sheet.SetColumnWidth(3,25*256);
//m_sheet.SetColumnWidth(4,10*256);
//m_sheet.SetColumnWidth(5,10*256);
}
//創(chuàng)建文件
FileStreamfile=newFileStream(filePath,FileMode.OpenOrCreate,FileAccess.Write);
//創(chuàng)建一個(gè)IO流
MemoryStreamms=newMemoryStream();
//寫(xiě)入到流
m_workbook.Write(ms);
//轉(zhuǎn)換為字節(jié)數(shù)組
byte[]bytes=ms.ToArray();
file.Write(bytes,0,bytes.Length);
file.Flush();
//釋放資源
bytes=null;
ms.Close();
ms.Dispose();
file.Close();
file.Dispose();
m_workbook.Close();
m_sheet=null;
m_workbook=null;
m_cellStyle=null;
m_datastyle=null;
m_font=null;
m_font12=null;
m_font20=null;
returntrue;
}
catch(Exceptionex)
{
returnfalse;
}
}
#region定義單元格常用到樣式
staticICellStyleGetcellstyle(IWorkbookwb,stylexlsstr)
{
try
{
//CreateFont()不能頻繁創(chuàng)建,會(huì)導(dǎo)致打開(kāi)EXCEL表的時(shí)候報(bào)如下錯(cuò)誤:
//此文件中的某些文本格式可能已經(jīng)更改,因?yàn)樗呀?jīng)超出最多允許的字體數(shù)。
if(m_font20==null)
{
m_font20=wb.CreateFont();
m_font20.FontHeightInPoints=20;
m_font20.FontName="微軟雅黑";
m_font20.Boldweight=(short)FontBoldWeight.Bold;
}
if(m_font12==null)
{
m_font12=wb.CreateFont();
m_font12.FontHeightInPoints=12;
m_font12.FontName="微軟雅黑";
m_font12.Boldweight=(short)FontBoldWeight.Bold;
}
if(m_font==null)
{
m_font=wb.CreateFont();
m_font.FontName="微軟雅黑";
}
//if(m_cellStyle==null)
//{
m_cellStyle=wb.CreateCellStyle();
//邊框
m_cellStyle.BorderBottom=NPOI.SS.UserModel.BorderStyle.Medium;
m_cellStyle.BorderLeft=NPOI.SS.UserModel.BorderStyle.Medium;
m_cellStyle.BorderRight=NPOI.SS.UserModel.BorderStyle.Medium;
m_cellStyle.BorderTop=NPOI.SS.UserModel.BorderStyle.Medium;
//邊框顏色
m_cellStyle.BottomBorderColor=HSSFColor.OliveGreen.Blue.Index;
m_cellStyle.TopBorderColor=HSSFColor.OliveGreen.Blue.Index;
//背景圖形
//cellStyle.FillBackgroundColor=HSSFColor.OLIVE_GREEN.BLUE.index;
//cellStyle.FillForegroundColor=HSSFColor.OLIVE_GREEN.BLUE.index;
m_cellStyle.FillForegroundColor=HSSFColor.White.Index;
//cellStyle.FillPattern=FillPatternType.NO_FILL;
m_cellStyle.FillBackgroundColor=HSSFColor.Blue.Index;
//水平對(duì)齊
m_cellStyle.Alignment=NPOI.SS.UserModel.HorizontalAlignment.Center;
//垂直對(duì)齊
m_cellStyle.VerticalAlignment=VerticalAlignment.Center;
//自動(dòng)換行
m_cellStyle.WrapText=false;
//縮進(jìn)
//cellStyle.Indention=0;
//}
//創(chuàng)建格式
if(m_datastyle==null)
{
m_datastyle=wb.CreateDataFormat();
}
//上面基本都是設(shè)共公的設(shè)置
//下面列出了常用的字段類型
switch(str)
{
casestylexls.頭:
//cellStyle.FillPattern=FillPatternType.LEAST_DOTS;
//設(shè)置為文本格式,也可以為text,即dataFormat.GetFormat("text");
m_cellStyle.DataFormat=m_datastyle.GetFormat("@");
m_cellStyle.SetFont(m_font20);
break;
casestylexls.列標(biāo)題:
//cellStyle.FillPattern=FillPatternType.LEAST_DOTS;
m_cellStyle.DataFormat=m_datastyle.GetFormat("@");
m_cellStyle.SetFont(m_font12);
break;
casestylexls.時(shí)間:
m_cellStyle.DataFormat=m_datastyle.GetFormat("yyyy/mm/dd");
m_cellStyle.SetFont(m_font);
break;
casestylexls.數(shù)字:
m_cellStyle.DataFormat=HSSFDataFormat.GetBuiltinFormat("0.00");
m_cellStyle.SetFont(m_font);
break;
casestylexls.錢:
m_cellStyle.DataFormat=m_datastyle.GetFormat("¥#,##0");
m_cellStyle.SetFont(m_font);
break;
casestylexls.url:
//IFontfontcolorblue=wb.CreateFont();
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 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ì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 中級(jí)社會(huì)工作者考試中的情感管理技能及試題及答案
- 考生模擬與實(shí)戰(zhàn)演練試題及答案
- 社會(huì)工作者的角色定位試題及答案
- 2025年網(wǎng)絡(luò)設(shè)計(jì)師考試實(shí)戰(zhàn)模擬試題及答案
- 英國(guó)留學(xué)選校測(cè)試題及答案
- 高精準(zhǔn)軟件評(píng)測(cè)師考試試題及答案預(yù)測(cè)
- 二級(jí)excel李東陽(yáng)試題及答案
- 新能源歷年面試題及答案
- 職業(yè)倫理及其實(shí)施試題及答案
- 備考2025年網(wǎng)絡(luò)規(guī)劃設(shè)計(jì)師的高效方法與試題及答案
- 動(dòng)漫產(chǎn)業(yè)協(xié)同創(chuàng)新與產(chǎn)業(yè)鏈協(xié)同效應(yīng)動(dòng)態(tài)變化趨勢(shì)及對(duì)策建議報(bào)告
- 2025年教育管理與政策研究考試試題及答案
- 2025年江蘇省南京市玄武區(qū)中考一模歷史試卷
- 2025年新媒體運(yùn)營(yíng)專員面試題及答案
- 2019人教版高中數(shù)學(xué)B版 必修第3冊(cè)《第七章 三角函數(shù)》大單元整體教學(xué)設(shè)計(jì)2020課標(biāo)
- 人防知識(shí)考試試題及答案
- 《企業(yè)數(shù)據(jù)安全策略》課件
- 醫(yī)院傳染病管理工作小組及職責(zé)
- 保險(xiǎn)公司迎檢工作方案
- 除顫儀的使用方法及操作流程
- 規(guī)范網(wǎng)絡(luò)設(shè)備管理制度
評(píng)論
0/150
提交評(píng)論