gpt4 book ai didi

c# - NPOI 设置不同的单元格格式

转载 作者:行者123 更新时间:2023-12-02 01:51:20 31 4
gpt4 key购买 nike

我在每个单元格中设置不同的格式时遇到问题,我想将数字格式设置为千位分隔符和带有 3 位小数的千位分隔符,当数字不是整数时,这是我的代码,我认为问题看起来像是设置了每个单元格格式通过for循环中最后的格式设置

所以输出应该是这样的12345 -> 12345; 425 -> 425; 41,2 -> 41,2; 4578,25 -> 4 578,25

        short doubleFormat = hssfOutputWorkBook.CreateDataFormat().GetFormat("#,##0.###");
short intFormat = hssfOutputWorkBook.CreateDataFormat().GetFormat("#,##0");
for (i = 0; i <= unorderedSheet.LastRowNum; i++)
{
NPOI.SS.UserModel.IRow newRow = orderedSheet.CreateRow(i);
NPOI.SS.UserModel.IRow oldRow = unorderedSheet.GetRow(i);
if (oldRow != null)
{
foreach (ICell oldCell in oldRow.Cells)
{
ICell newCell = newRow.CreateCell(mapping[n]);
switch (oldCell.CellType)
{
case CellType.NUMERIC:
newCell.SetCellType(CellType.NUMERIC);
newCell.SetCellValue(oldCell.NumericCellValue);
if (numberHasDecimals(oldCell.NumericCellValue))
{
newCell.CellStyle.DataFormat = doubleFormat;
}
else
{
newCell.CellStyle.DataFormat = intFormat;
}
break;
default:
newCell.SetCellValue(oldCell.ToString());
break;
}}}}

最佳答案

static ICellStyle _doubleCellStyle = null;
static ICellStyle _intCellStyle = null;
static void SettingDifferentCellFormat( HSSFWorkbook hssfOutputWorkBook, ISheet orderedSheet, ISheet unorderedSheet ) {

//short doubleFormat = hssfOutputWorkBook.CreateDataFormat().GetFormat( "#,##0.###" );
//short intFormat = hssfOutputWorkBook.CreateDataFormat().GetFormat( "#,##0" );

if ( _doubleCellStyle == null ) {
_doubleCellStyle = hssfOutputWorkBook.CreateCellStyle();
_doubleCellStyle.DataFormat = hssfOutputWorkBook.CreateDataFormat().GetFormat( "#,##0.###" );
}

if ( _intCellStyle == null ) {
_intCellStyle = hssfOutputWorkBook.CreateCellStyle();
_intCellStyle.DataFormat = hssfOutputWorkBook.CreateDataFormat().GetFormat( "#,##0" );
}

for ( int i = 0; i <= unorderedSheet.LastRowNum; i++ ) {

NPOI.SS.UserModel.IRow newRow = orderedSheet.CreateRow( i );
NPOI.SS.UserModel.IRow oldRow = unorderedSheet.GetRow( i );

const int mapping_n_ = 0;

if ( oldRow != null ) {
foreach ( ICell oldCell in oldRow.Cells ) {

ICell newCell = newRow.CreateCell( mapping_n_ );
bool numberHasDecimals = true;

switch ( oldCell.CellType ) {

case CellType.NUMERIC:

newCell.SetCellType( CellType.NUMERIC );
newCell.SetCellValue( oldCell.NumericCellValue );

if ( numberHasDecimals ) {
//newCell.CellStyle.DataFormat = doubleFormat;
newCell.CellStyle = _doubleCellStyle;
} else {
//newCell.CellStyle.DataFormat = intFormat;
newCell.CellStyle = _intCellStyle;
}
break;
default:
newCell.SetCellValue( oldCell.ToString() );
break;
}
}
}
}

}//SettingDifferentCellFormat

关于c# - NPOI 设置不同的单元格格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419400/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com