NPOI 自定义单元格背景颜色 XSSFWorkbook - Excel

原文网址  https://www.cnblogs.com/love-zf/p/7450409.html

 

BorderStyle.Thin  全称为 NPOI.SS.UserModel.BorderStyle.Thin

最后那个关于报错的修改,亲测有效.

 

网上找到了,HSSFWorkbook自定义颜色的例子(讲的还挺细致的),但是XSSFWorkbook确没找到...研究了一下,坑掉了一地...

NPOI.XSSF.UserModel.XSSFWorkbook xssfworkbook = new NPOI.XSSF.UserModel.XSSFWorkbook();

 

方案壹:>>XSSFCellStyle

XSSFCellStyle rowsStyleColor = (XSSFCellStyle)xssfworkbook.CreateCellStyle();
XSSFColor xssfColor = new XSSFColor();
//根据自己需要设置RGB
byte[] colorRgb = { (byte)252, (byte)139, (byte)139 };
xssfColor.SetRgb(colorRgb);
rowsStyleColor.FillForegroundColorColor = xssfColor;
rowsStyleColor.FillPattern = FillPattern.SolidForeground;

 方案贰:>>ICellStyle

ICellStyle rowsStyleColor = (XSSFCellStyle)xssfworkbook.CreateCellStyle();
rowsStyleColor.Alignment = HorizontalAlignment.Center;
rowsStyleColor.VerticalAlignment = VerticalAlignment.Center;
rowsStyleColor.BorderBottom = BorderStyle.Thin;
rowsStyleColor.BorderLeft = BorderStyle.Thin;
rowsStyleColor.BorderRight = BorderStyle.Thin;
rowsStyleColor.BorderTop = BorderStyle.Thin;
rowsStyleColor.WrapText = true;
//设置背景颜色...
rowsStyleColor.FillForegroundColor = 0;
rowsStyleColor.FillPattern = FillPattern.SolidForeground;
((XSSFColor)rowsStyleColor.FillForegroundColorColor).SetRgb(new byte[] { 252, 139, 139 });

 

感觉挺别扭的...一点搞不好,就是错误...

 

其他的报错:

//****************************文件流...
public ActionResult ExportExcelFile()
{
    byte[] streamData = null;

    try
    {
    MemoryStream file = new MemoryStream();    
       workbook.Write(file);
    /*这个错误导致我一直以为NPOI不能导出不报错的.xlsx类型的Excel呢!!!···*/   
       streamData = file.ToArray();//这种写法就可以的...     //streamData =file.GetBuffer();//用这么的写法,导出的Excel,就是报错,类似格式不正确,需要修复才能打开...

        if (streamData == null || streamData.Length == 0) { return Content("无数据供导出。"); }

        Response.Charset = "UTF-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "filename=Test.xlsx");
        Response.AddHeader("Content-Length", streamData.LongLength.ToString());
        Response.BinaryWrite(streamData);
        Response.Flush();
        Response.End();

        return null;
    }
    catch (Exception ex)
    {
        return Content("未知错误>>>");
    }
}

 

NPOI 自定义单元格背景颜色 XSSFWorkbook - Excel

上一篇:SSIS数据同步系统


下一篇:quick-cocos2d-x api构建文档