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

时间:2023-03-09 23:41:31
NPOI 自定义单元格背景颜色 XSSFWorkbook - Excel

x

网上找到了,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), (byte), (byte) };
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 = ;
rowsStyleColor.FillPattern = FillPattern.SolidForeground;
((XSSFColor)rowsStyleColor.FillForegroundColorColor).SetRgb(new byte[] { , , });

x

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

x

其他的报错:

//****************************文件流...
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("未知错误>>>");
    }
}