我正在使用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


是否有一种“清洁”的方法来执行此操作?现在,我必须手动为单个单元格添加字体。我已经尝试了多种方法在Internet上执行此操作,但似乎没有任何效果。您是否有经过测试的应用方法特定列或行的样式?

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/

10-14 16:57
查看更多