我不明白为什么会发生这种情况,首先我尝试将粗体文本应用于第一行中的列标题,然后我想将标题单元格的边框设置为中,但此中边框样式应用于所有单元格在表中。下面相同的代码还有更多问题:
这是我的代码(使用 NPOI 库处理):
private void CreateATest(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
HSSFWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("NPOI");
IRow row = sheet.CreateRow(0);
row.RowStyle = wb.CreateCellStyle();
row.RowStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
row.RowStyle.VerticalAlignment = VerticalAlignment.CENTER;
row.RowStyle.WrapText = true;
IFont font = wb.CreateFont();
font.Boldweight = 3;
font.Color = (short) ColorTranslator.ToWin32(Color.Red);
font.FontHeight = 30;
row.RowStyle.SetFont(font);
int i = 0;
foreach (string header in new string[] { "ID", "Name", "Age" })
{
row.CreateCell(i++).SetCellValue(header);
row.Cells[i - 1].CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.MEDIUM;
row.Cells[i - 1].CellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.MEDIUM;
row.Cells[i - 1].CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.MEDIUM;
}
row.Cells[i - 1].CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.MEDIUM;
Random rand = new Random();
for (i = 1; i < 1000; i++)
{
IRow row1 = sheet.CreateRow(i);
for (int j = 0; j < 3; j++)
{
row1.CreateCell(j).SetCellValue(rand.Next(100));
}
}
wb.Write(fs);
fs.Close();
}
请帮我修复它,我对 NPOI 很陌生,刚刚尝试使用它。我们将非常感谢您的帮助。 谢谢。 (<--- I don't know why this 'Thanks' can't jump to the next line even I typed Enter before typing it)
格式问题是由于 Excel 格式化插入行的方式造成的。他们从上面的行中获取风格信息。您可以通过将行格式设置为粗体,然后在紧邻下方插入一行来测试这一点 - 新行也将加粗。
您可以尝试先插入其余行,然后再对标题行进行格式化。
这是解决方案 - 我也遇到了同样的问题。 您需要创建一个离散的 ICellStyle 并将其分配给单元格的 CellStyle,而不是仅仅在单元格当前的 CellStyle 上调用“SetFont()”。
我遇到了同样的问题,即样式应用于所有单元格。我评论了导致它的行,下一行是有效的行(以及 ICellStyle 部分):
let workbook:HSSFWorkbook = new HSSFWorkbook()
let worksheet:ISheet = workbook.CreateSheet(sheetName)
let fontbold = workbook.CreateFont()
fontbold.Boldweight <- (int16 FontBoldWeight.Bold)
fontbold.FontHeightInPoints <- 10s
fontbold.FontName <- "Arial"
let cellstylebold:ICellStyle = workbook.CreateCellStyle()
cellstylebold.SetFont(fontbold)
let row:IRow = worksheet.CreateRow(0)
for h in 0..headers.Length-1 do
let cell = row.CreateCell(h)
cell.SetCellValue(headers.[h])
//cell.CellStyle.SetFont(fontbold)
cell.CellStyle <- cellstylebold
Rory 请求的一个可能的解决方案是在创建单元格时设置 CellStyle,然后才使用 GetCell(x) 设置值。
我有同样的错误,因为我在创建它后尝试更改 CellStyle,并解决了更改顺序的问题,以这种方式:
//CREATE STYLE
ICellStyle styleCenter1 = hssfworkbook.CreateCellStyle();
styleCenter1.Alignment = HorizontalAlignment.Center;
styleCenter1.VerticalAlignment = VerticalAlignment.Center;
styleCenter1.WrapText = true;
styleCenter1.SetFont(font1);
//CREATE ROW
IRow row = sheet1.CreateRow(z);
//SETTING CELLSTYLE WHILE CREATING CELL
row.CreateCell(0).CellStyle = styleCenter1;
//SETTING CELLVALUE AFTER
row.GetCell(0).SetCellValue(listaSocieta[x]);
再见,
雷蒙多