我正在使用 NPOI 将我的数据导出到 excel。问题是我发现很难进行任何类型的图形更改。
这是我现在用来将粗体字体应用到我的单元格的方法。
//Create new Excel workbook
var workbook = new HSSFWorkbook();
//Create new Excel sheet
var sheet = workbook.CreateSheet();
//Create a header row
var headerRow = sheet.CreateRow(0);
var boldFont = workbook.CreateFont();
boldFont.FontHeightInPoints = 11;
boldFont.FontName = "Calibri";
boldFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
int cellCounter = 0;
//day
var cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Day");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont);
//month
cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Month");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont);
//year
cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Year");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont);
//machine name
cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Machine unique name");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont); //and so on
有没有更干净的方法来做到这一点?现在我必须手动为单个单元格添加字体。我在互联网上尝试了很多方法来做到这一点,但似乎没有任何效果。你有测试过的吗将样式应用于特定列或行的方法?
OffTopic:如果不能,您能否为我提供一些优秀的开源库,这些库具有良好的文档和允许导出 excel 的支持(学习新的 dll 很痛苦,但是...:) 您能做什么)?
最佳答案
我正在做类似的事情并修改了我对它的看法以供您使用:
private string[] columnHeaders =
{
"Day",
"Month",
"Year",
"Machine Unique Name"
}
private void buildSheet(HSSFWorkbook wb, DataTable data, string sheetName)
{
var cHelp = wb.GetCreationHelper();
var sheet = wb.CreateSheet(sheetName);
HSSFFont hFont = (HSSFFont)wb.CreateFont();
hFont.FontHeightInPoints = 11;
hFont.FontName = "Calibri";
hFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
HSSFCellStyle hStyle = (HSSFCellStyle)wb.CreateCellStyle();
hStyle.SetFont(hFont);
IRow headerRow = sheet.CreateRow(1);
int cellCount = 1;
foreach (string str in columnHeaders)
{
HSSFCell cell = (HSSFCell)headerRow.CreateCell(cellCount);
cell.SetCellValue(cHelp.CreateRichTextString((str)));
cell.CellStyle = hStyle;
cellCount += 1;
}
这会遍历从第二个单元格 (cellCount = 1) 第二行 (sheet.CreateRow(1)) 开始的许多标题。
关于c# - NPOI 将字体应用于整行单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550835/