因為我的個人網(wǎng)站 已經(jīng)啟用,博客園的內容已經(jīng)不再更新。請訪問我的個人網(wǎng)站獲取這篇文章的最新內容,C# 中 NPOI 庫讀寫 Excel 文件的方法
NPOI 是開源的 POI 項目的.NET版,可以用來讀寫Excel,Word,PPT文件。在處理Excel文件上,NPOI 可以同時兼容 xls 和 xlsx。官網(wǎng)提供了一份 Examples,給出了很多應用場景的例子,打包好的二進制文件類庫,也僅有幾MB,使用非常方便。
讀Excel
NPOI 使用 HSSFWorkbook 類來處理 xls,XSSFWorkbook 類來處理 xlsx,它們都繼承接口 IWorkbook ,因此可以通過 IWorkbook 來統(tǒng)一處理 xls 和 xlsx 格式的文件。
以下是簡單的例子
public void ReadFromExcelFile(string filePath)
{
IWorkbook wk = null;
string extension = System.IO.Path.GetExtension(filePath);
try
{
FileStream fs = File.OpenRead(filePath);
if (extension.Equals(".xls"))
{
//把xls文件中的數(shù)據(jù)寫入wk中
wk = new HSSFWorkbook(fs);
}
else
{
//把xlsx文件中的數(shù)據(jù)寫入wk中
wk = new XSSFWorkbook(fs);
}
fs.Close();
//讀取當前表數(shù)據(jù)
ISheet sheet = wk.GetSheetAt(0);
IRow row = sheet.GetRow(0); //讀取當前行數(shù)據(jù)
//LastRowNum 是當前表的總行數(shù)-1(注意)
int offset = 0;
for (int i = 0; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i); //讀取當前行數(shù)據(jù)
if (row != null)
{
//LastCellNum 是當前行的總列數(shù)
for (int j = 0; j < row.LastCellNum; j++)
{
//讀取該行的第j列數(shù)據(jù)
string value = row.GetCell(j).ToString();
Console.Write(value.ToString() + " ");
}
Console.WriteLine("\n");
}
}
}
catch (Exception e)
{
//只在Debug模式下才輸出
Console.WriteLine(e.Message);
}
}
Excel中的單元格是有不同數(shù)據(jù)格式的,例如數(shù)字,日期,字符串等,在讀取的時候可以根據(jù)格式的不同設置對象的不同類型,方便后期的數(shù)據(jù)處理。
//獲取cell的數(shù)據(jù),并設置為對應的數(shù)據(jù)類型
public object GetCellValue(ICell cell)
{
object value = null;
try
{
if (cell.CellType != CellType.Blank)
{
switch (cell.CellType)
{
case CellType.Numeric:
// Date comes here
if (DateUtil.IsCellDateFormatted(cell))
{
value = cell.DateCellValue;
}
else
{
// Numeric type
value = cell.NumericCellValue;
}
break;
case CellType.Boolean:
// Boolean type
value = cell.BooleanCellValue;
break;
case CellType.Formula:
value = cell.CellFormula;
break;
default:
// String type
value = cell.StringCellValue;
break;
}
}
}
catch (Exception)
{
value = "";
}
return value;
}
特別注意的是CellType 中沒有Date,而日期類型的數(shù)據(jù)類型是Numeric ,其實日期的數(shù)據(jù)在Excel中也是以數(shù)字的形式存儲。可以使用DateUtil.IsCellDateFormatted 方法來判斷是否是日期類型。
有了GetCellValue 方法,寫數(shù)據(jù)到Excel中的時候就要有SetCellValue 方法,缺的類型可以自己補。
//根據(jù)數(shù)據(jù)類型設置不同類型的cell
public static void SetCellValue(ICell cell, object obj)
{
if (obj.GetType() == typeof(int))
{
cell.SetCellValue((int)obj);
}
else if (obj.GetType() == typeof(double))
{
cell.SetCellValue((double)obj);
}
else if (obj.GetType() == typeof(IRichTextString))
{
cell.SetCellValue((IRichTextString)obj);
}
else if (obj.GetType() == typeof(string))
{
cell.SetCellValue(obj.ToString());
}
else if (obj.GetType() == typeof(DateTime))
{
cell.SetCellValue((DateTime)obj);
}
else if (obj.GetType() == typeof(bool))
{
cell.SetCellValue((bool)obj);
}
else
{
cell.SetCellValue(obj.ToString());
}
}
cell.SetCellValue() 方法只有四種重載方法,參數(shù)分別是string , bool , DateTime , double , IRichTextString
設置公式使用cell.SetCellFormula(string formula)
寫Excel
以下是簡單的例子,更多信息可以參見官網(wǎng)提供的Examples。
public void WriteToExcel(string filePath)
{
//創(chuàng)建工作薄
IWorkbook wb;
string extension = System.IO.Path.GetExtension(filePath);
//根據(jù)指定的文件格式創(chuàng)建對應的類
if (extension.Equals(".xls"))
{
wb = new HSSFWorkbook();
}
else
{
wb = new XSSFWorkbook();
}
ICellStyle style1 = wb.CreateCellStyle();//樣式
style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊方式
style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊方式
//設置邊框
style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style1.WrapText = true;//自動換行
ICellStyle style2 = wb.CreateCellStyle();//樣式
IFont font1 = wb.CreateFont();//字體
font1.FontName = "楷體";
font1.Color = HSSFColor.Red.Index;//字體顏色
font1.Boldweight = (short)FontBoldWeight.Normal;//字體加粗樣式
style2.SetFont(font1);//樣式里的字體設置具體的字體樣式
//設置背景色
style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
style2.FillPattern = FillPattern.SolidForeground;
style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊方式
style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊方式
ICellStyle dateStyle = wb.CreateCellStyle();//樣式
dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊方式
dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊方式
//設置數(shù)據(jù)顯示格式
IDataFormat dataFormatCustom = wb.CreateDataFormat();
dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
//創(chuàng)建一個表單
ISheet sheet = wb.CreateSheet("Sheet0");
//設置列寬
int[] columnWidth = { 10, 10, 20, 10 };
for (int i = 0; i < columnWidth.Length; i++)
{
//設置列寬度,256*字符數(shù),因為單位是1/256個字符
sheet.SetColumnWidth(i, 256 * columnWidth[i]);
}
//測試數(shù)據(jù)
int rowCount = 3, columnCount = 4;
object[,] data = {
{"列0", "列1", "列2", "列3"},
{"", 400, 5.2, 6.01},
{"", true, "2014-07-02", DateTime.Now}
//日期可以直接傳字符串,NPOI會自動識別
//如果是DateTime類型,則要設置CellStyle.DataFormat,否則會顯示為數(shù)字
};
IRow row;
ICell cell;
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i);//創(chuàng)建第i行
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//創(chuàng)建第j列
cell.CellStyle = j % 2 == 0 ? style1 : style2;
//根據(jù)數(shù)據(jù)類型設置不同類型的cell
object obj = data[i, j];
SetCellValue(cell, data[i, j]);
//如果是日期,則設置日期顯示的格式
if (obj.GetType() == typeof(DateTime))
{
cell.CellStyle = dateStyle;
}
//如果要根據(jù)內容自動調整列寬,需要先setCellValue再調用
//sheet.AutoSizeColumn(j);
}
}
//合并單元格,如果要合并的單元格中都有數(shù)據(jù),只會保留左上角的
//CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的單元格
CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
sheet.AddMergedRegion(region);
try
{
FileStream fs = File.OpenWrite(filePath);
wb.Write(fs);//向打開的這個Excel文件中寫入表單并保存。
fs.Close();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
如果想要設置單元格為只讀或可寫,可以參考這里,方法如下:
ICellStyle unlocked = wb.CreateCellStyle();
unlocked.IsLocked = false;//設置該單元格為非鎖定
cell.SetCellValue("未被鎖定");
cell.CellStyle = unlocked;
...
//保護表單,password為解鎖密碼
//cell.CellStyle.IsLocked = true;的單元格將為只讀
sheet.ProtectSheet("password");
cell.CellStyle.IsLocked 默認就是true,因此sheet.ProtectSheet("password") 一定要執(zhí)行,才能實現(xiàn)鎖定單元格,對于不想鎖定的單元格,就一定要設置cell 的CellStyle 中的IsLocked = false
|