緣起
好久沒搞過npoi了,本來就想着用NPOI編輯一下模板,但是寫入值要麼是打不開,要麼是打開報一堆警告消息。
解決方案
最新版本的NPOI處理.xlsx格式有bug,建議降級到NPOI2.4.1
或者是使用xls格式。
網上的神們提供的操作步驟是:
- 讀取excel,然後關閉filestream
using (FileStream fs = File.OpenRead(fileName)) { if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); fs.Close(); }
- 修改excel
cell.SetCellValue(value);
- 打開excel,並賦予它寫的權限,然後保存即可
workbook.Write(fs)
下面是我的代碼,僅供參考:
public void SetExcelCellValue(string fileName, int iSheetIndex, int iRow, int iCol, object value)
{
try
{
if (File.Exists(fileName))
{
IWorkbook workbook = null;
using (FileStream fs = File.OpenRead(fileName))
{
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
fs.Close();
}
ISheet sheet = workbook.GetSheetAt(iSheetIndex);
IRow row = sheet.GetRow(iRow);
if (row == null)
{
row = sheet.CreateRow(iRow);
}
ICell cell = row.GetCell(iCol);
if (cell == null)
{
row.CreateCell(iCol);
}
if (value is int)
{
cell.SetCellValue((int)value);
}
else if (value is double)
{
cell.SetCellValue((double)value);
}
else if (value is string)
{
cell.SetCellValue(value.ToString());
}
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write))
{
workbook.Write(fs);
workbook.Close();
fs.Close();
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog(typeof(ExcelHelper), ex, "設置單元格出錯!");
}
}
參考鏈接:
- NPOI操作Excel 踩坑記
- https://github.com/tonyqus/npoi/issues/182