NPOI 如何更新工作簿中的单元格格式
NPOI How to update cell format in workbook
我正在尝试按如下方式格式化单元格。
输入“99.99999”
预期输出“99.999”
public void UpdateCellToExistingWorkBook(int x, int y, string value,
string format)
{
var sheet = _hssfworkbook.GetSheet(_sheetName);
try
{
var cellStyle = _hssfworkbook.CreateCellStyle();
if (format != null)
{
cellStyle.DataFormat = _hssfworkbook.CreateDataFormat().GetFormat(format);
//cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("00.000");
}
var cell = CellUtil.CreateCell(sheet.CreateRow(x), y, value, cellStyle);
cell.SetCellType(CellType.Numeric);
WriteToFile(_path);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
我做错了什么?
这是我在编辑现有 Excel 文件时的示例(请注意,我的 Excel 本地化为使用十进制逗号而不是点):
public static MemoryStream ListExcel2(string path)
{
XSSFWorkbook hssfwb;
using (FileStream file = new FileStream(Path.Combine(path, "Test.xlsx"), FileMode.Open, FileAccess.Read))
{
hssfwb = new XSSFWorkbook(file);
file.Close();
}
ICellStyle _double = hssfwb.CreateCellStyle();
_double.DataFormat = hssfwb.CreateDataFormat().GetFormat("#,###.###");
ISheet sheet = hssfwb.GetSheetAt(0);
IRow row = sheet.GetRow(7);
ICell cell = row.GetCell(1);
double value = 999.912123123d;
cell.SetCellValue(value);
cell.CellStyle = _double;
using (var memoryStream = new MemoryStream()) //creating memoryStream
{
hssfwb.Write(memoryStream);
return memoryStream;
}
}
输出(在模板中,单元格 B8 的格式为“常规”,并根据上面的代码更改为自定义数字):
我正在尝试按如下方式格式化单元格。
输入“99.99999” 预期输出“99.999”
public void UpdateCellToExistingWorkBook(int x, int y, string value,
string format)
{
var sheet = _hssfworkbook.GetSheet(_sheetName);
try
{
var cellStyle = _hssfworkbook.CreateCellStyle();
if (format != null)
{
cellStyle.DataFormat = _hssfworkbook.CreateDataFormat().GetFormat(format);
//cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("00.000");
}
var cell = CellUtil.CreateCell(sheet.CreateRow(x), y, value, cellStyle);
cell.SetCellType(CellType.Numeric);
WriteToFile(_path);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
我做错了什么?
这是我在编辑现有 Excel 文件时的示例(请注意,我的 Excel 本地化为使用十进制逗号而不是点):
public static MemoryStream ListExcel2(string path)
{
XSSFWorkbook hssfwb;
using (FileStream file = new FileStream(Path.Combine(path, "Test.xlsx"), FileMode.Open, FileAccess.Read))
{
hssfwb = new XSSFWorkbook(file);
file.Close();
}
ICellStyle _double = hssfwb.CreateCellStyle();
_double.DataFormat = hssfwb.CreateDataFormat().GetFormat("#,###.###");
ISheet sheet = hssfwb.GetSheetAt(0);
IRow row = sheet.GetRow(7);
ICell cell = row.GetCell(1);
double value = 999.912123123d;
cell.SetCellValue(value);
cell.CellStyle = _double;
using (var memoryStream = new MemoryStream()) //creating memoryStream
{
hssfwb.Write(memoryStream);
return memoryStream;
}
}
输出(在模板中,单元格 B8 的格式为“常规”,并根据上面的代码更改为自定义数字):