NPOI是開源的POI項目的.NET版,可以用來讀寫Excel,Word,PPT文件。在處理Excel文件上,NPOI 可以同時兼容xls 和xlsx。官網提供了一份Examples,給出了很多應用場景的例子,打包好的二進製文件類庫,也僅有幾MB,使用非常方便。
讀Excel
NPOI 使用 HSSFWorkbook
類來處理xls,XSSFWorkbook
類來處理xlsx,它們都繼承接口IWorkbook
,因此可以通過 IWorkbook
來統一處理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"))
{
wk = new HSSFWorkbook(fs);
}
else
{
wk = new XSSFWorkbook(fs);
}
fs.Close();
ISheet sheet = wk.GetSheetAt(0);
IRow row = sheet.GetRow(0);
int offset = 0;
for (int i = 0; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i);
if (row != null)
{
for (int j = 0; j < row.LastCellNum; j++)
{
string value = row.GetCell(j).ToString();
Console.Write(value.ToString() + " ");
}
Console.WriteLine("\n");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Excel中的單元格是有不同數據格式的,例如數字,日期,字符串等,在讀取的時候可以根據格式的不同設置對象的不同類型,方便後期的數據處理。
public object GetCellValue(ICell cell)
{
object value = null;
try
{
if (cell.CellType != CellType.Blank)
{
switch (cell.CellType)
{
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
value = cell.DateCellValue;
}
else
{
value = cell.NumericCellValue;
}
break;
case CellType.Boolean:
value = cell.BooleanCellValue;
break;
case CellType.Formula:
value = cell.CellFormula;
break;
default:
value = cell.StringCellValue;
break;
}
}
}
catch (Exception)
{
value = "";
}
return value;
}
特別注意的是CellType
中沒有Date,而日期類型的數據類型是Numeric
,其實日期的數據在Excel中也是以數字的形式存儲。可以使用DateUtil.IsCellDateFormatted
方法來判斷是否是日期類型。
有了GetCellValue
方法,寫數據到Excel中的時候就要有SetCellValue
方法,缺的類型可以自己補。
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()
方法只有四種重載方法,參數分別是string
, bool
, DateTime
, double
,IRichTextString
設置公式使用cell.SetCellFormula(string formula)
寫Excel
以下是簡單的例子,更多信息可以參見官網提供的Examples。
public void WriteToExcel(string filePath)
{
IWorkbook wb;
string extension = System.IO.Path.GetExtension(filePath);
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;
IDataFormat dataFormatCustom = wb.CreateDataFormat();
dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
ISheet sheet = wb.CreateSheet("Sheet0");
int[] columnWidth = { 10, 10, 20, 10 };
for (int i = 0; i < columnWidth.Length; i++)
{
sheet.SetColumnWidth(i, 256 * columnWidth[i]);
}
int rowCount = 3, columnCount = 4;
object[,] data = {
{"列0", "列1", "列2", "列3"},
{"", 400, 5.2, 6.01},
{"", true, "2014-07-02", DateTime.Now}
};
IRow row;
ICell cell;
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);
cell.CellStyle = j % 2 == 0 ? style1 : style2;
object obj = data[i, j];
SetCellValue(cell, data[i, j]);
if (obj.GetType() == typeof(DateTime))
{
cell.CellStyle = dateStyle;
}
}
}
CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
sheet.AddMergedRegion(region);
try
{
FileStream fs = File.OpenWrite(filePath);
wb.Write(fs);
fs.Close();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
如果想要設置單元格為只讀或可寫,可以參考這裡,方法如下:
ICellStyle unlocked = wb.CreateCellStyle();
unlocked.IsLocked = false;
cell.SetCellValue("未被锁定");
cell.CellStyle = unlocked;
...
sheet.ProtectSheet("password");
cell.CellStyle.IsLocked
默認就是true,因此sheet.ProtectSheet("password")
一定要執行,才能實現鎖定單元格,對於不想鎖定的單元格,就一定要設置cell
的CellStyle
中的IsLocked = false