首页 > 其他分享 >Npoi操作Excel单元格合并

Npoi操作Excel单元格合并

时间:2024-03-03 15:36:25浏览次数:17  
标签:CellStyle sheet ICell 单元格 Excel modelCount CreateCell Npoi cellStyleBgColor

  public async Task<byte[]> ExportNewReportByQuotationId(Guid quotationId)
    {

        //string sql = @$"select ""Id"" as ModelId,  (q.qq).key as key,(q.qq).value as  myValue  from(with a as( select ""Id"" ,""Customer"" ,""Family"" ,""ModelPN""  from ""Eme_ProductModelMain"" epmm  limit 3) select ""Id"",jsonb_each(row_to_json(a)::jsonb-'qqq'::varchar)as qq from a )q ";
        // eqpm.""QuotationId"" ,eqpm.""ProductId"" ,
        string sql = @$"select epmm.""ModelPN""  from  ""qq_GoodsProductModels"" eqpm  left join ""qq_ProductModelMain"" epmm  on eqpm.""ProductId"" =epmm.""Id""  where eqpm.""QuotationId""='{quotationId}'";
        var listProductPns = await DbScoped.SugarScope.Ado.SqlQueryAsync<string>(sql);
        int modelCount = listProductPns.Count;


        IWorkbook wookbook = new XSSFWorkbook();
        ISheet sheet = wookbook.CreateSheet("IL");
        int rowIndex = 0;//第几行
        IRow headRow1 = sheet.CreateRow(rowIndex);
        headRow1.Height = 350;
        ICellStyle cellStyleBgColor = wookbook.CreateCellStyle();
        cellStyleBgColor.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        cellStyleBgColor.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        cellStyleBgColor.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        cellStyleBgColor.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;

        ICell cellhead1 = headRow1.CreateCell(0);
        cellhead1.SetCellValue("");
        cellhead1.CellStyle = cellStyleBgColor;
        for (int mp = 0; mp < modelCount; mp++)
        {
            int mindex = mp + 1;
            ICell cellhead2 = headRow1.CreateCell(mindex);
            cellhead2.CellStyle = cellStyleBgColor;
            cellhead2.SetCellValue("HC Required(HC Qty)");//first input
        }
        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 1, modelCount));
        sheet.SetColumnWidth(1, Encoding.UTF8.GetBytes("HC Required(HC Qty)").Length * 256 / 2 + 100);
        sheet.SetColumnWidth(2, Encoding.UTF8.GetBytes("HC Required(HC Qty)").Length * 256 / 2 + 100);


        ICell cellhead_b2 = headRow1.CreateCell(modelCount + 1);
        cellhead_b2.SetCellValue("Rate");
        cellhead_b2.CellStyle = cellStyleBgColor;

        ICell cellhead_b1 = headRow1.CreateCell(modelCount + 2);
        cellhead_b1.SetCellValue("Remark");
        cellhead_b1.CellStyle = cellStyleBgColor;



        rowIndex += 1;
        IRow headRow2 = sheet.CreateRow(rowIndex);
        ICell cell1 = headRow2.CreateCell(0);
        cell1.SetCellValue("HC List");
        cell1.CellStyle = cellStyleBgColor;
        sheet.SetColumnWidth(0, Encoding.UTF8.GetBytes("Materials Supervisors Mfg Tier 1").Length * 256 + 100);
        for (int p = 0; p < modelCount; p++)
        {
            int pindex = p + 1;
            ICell cell2 = headRow2.CreateCell(pindex);
            cell2.SetCellValue(listProductPns[p]);
            cell2.CellStyle = cellStyleBgColor;
        }
        int backIndex = modelCount + 1;
        ICell cellb2 = headRow2.CreateCell(backIndex);
        cellb2.SetCellValue("Rate");
        cellb2.CellStyle = cellStyleBgColor;
        ICell cellb1 = headRow2.CreateCell(backIndex + 1);
        cellb1.SetCellValue("Remark");
        cellb1.CellStyle = cellStyleBgColor;

        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 1, modelCount + 1, modelCount + 1));
        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 1, modelCount + 2, modelCount + 2));

        AssmblyExcelModel(modelCount, sheet, cellStyleBgColor);

        string cpath = Directory.GetCurrentDirectory();
        Console.WriteLine("=====================" + cpath);
        string fulpath = Path.Combine(cpath, "wwwroot/myfiles/1.xlsx");
        using var file = File.Create(fulpath);
        wookbook.Write(file);

        MemoryStream stream = new MemoryStream();
        FileStream fileStream = new FileStream(fulpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        fileStream.CopyTo(stream);

        byte[] by = stream.ToArray();
        stream.Dispose();
        fileStream.Dispose();
        return by;
    }


    private void AssmblyExcelModel(int modelCount, ISheet sheet, ICellStyle cellStyleBgColor)
    {
        //到时可以配置出去
        var templateStr = ConnectionJsonDto.ExportILLeftNames.Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();
        for (int R = 0; R < templateStr.Count; R++)
        {
            int dataRow = R + 2;
            IRow row = sheet.CreateRow(dataRow);
            ICell cell = row.CreateCell(0);
            cell.SetCellValue(templateStr[R]);
            cell.CellStyle = cellStyleBgColor;
            for (int p = 0; p < modelCount; p++)
            {
                int pmodelIndex = p + 1;
                ICell cell2 = row.CreateCell(pmodelIndex);
                cell2.SetCellValue("");
                cell2.CellStyle = cellStyleBgColor;
            }

            ICell cell_back2 = row.CreateCell(modelCount + 1);
            cell_back2.SetCellValue("");
            cell_back2.CellStyle = cellStyleBgColor;

            ICell cell_back1 = row.CreateCell(modelCount + 2);
            cell_back1.SetCellValue("");
            cell_back1.CellStyle = cellStyleBgColor;

        }

    }

 

sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 1, modelCount));
(开始行,最后一行,开始列,最后一列)

标签:CellStyle,sheet,ICell,单元格,Excel,modelCount,CreateCell,Npoi,cellStyleBgColor
From: https://www.cnblogs.com/Fengge518/p/18050107

相关文章

  • 前端 xlsx js javascript 处理excel 数据展示 日期格式处理
     1、参考https://blog.csdn.net/Seven71111/article/details/107375712https://blog.csdn.net/weixin_44987713/article/details/130129282 https://blog.csdn.net/qq_57952018/article/details/134812452 2、存在的问题a、千年虫b、定义一个转换日期格式的方法(转成......
  • C# MiniExcel 导入和导出表格数据
    C#MiniExcel导入和导出表格数据1.首先从NuGet包里下载MIniExcel文件引入然后下面是一段Api控制器导入的代码导入导出的表格用.xlsx或.xls工作表///<summary>///上传文件到服务器端///</summary>///<paramname="formFile"></param>///<returns></returns>[......
  • python生成Excel文件减少使用内存
    1、openpyxl模块生成2、xlsxwriter模块contant_memory=True生成TRANSLATEwithxEnglishArabicHebrewPolishBulgarianHindiPortugueseCatalanHmongDawRomanianChineseSimplifiedHungarianRussianChineseTraditionalIndonesianSlovak......
  • Excel批量插入checkbox的宏代码
    来源网络,作为个人记录使用手动在excel中添加勾选框不复杂,但是添加多个的时候会很麻烦,特别是在做数据分析时,选择框属性应该绑定在对应单元格下,使用普通的填充方式无法到达要求,因此使用VBA宏命令批量添加.1Sub添加复选框()2'标题'3Application.ScreenUpdating=f......
  • Excel VBA
    VBA(VisualBasicforApplications)是VisualBasic的一种宏语言,是在其桌面应用程序中执行通用的自动化(OLE)任务的编程语言。主要能用来扩展Windows的应用程序功能,特别是MicrosoftOffice软件。它也可说是一种应用程式视觉化的Basic脚本。Office取得巨大成功的一个重要原因就是V......
  • WPF DataGrid下的单元格嵌入CheckBox列表
    <DataGridWidth="auto"Height="auto"AutoGenerateColumns="False"CanUserAddRows="False"GridLinesVisibility="All">        <DataGrid.Columns><DataGridTempla......
  • Java中使用Jsoup实现网页内容爬取与Html内容解析并使用EasyExcel实现导出为Excel文件
    场景Pythont通过request以及BeautifulSoup爬取几千条情话:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/87348030Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/124182289Jsoup......
  • Web自动化实战:Excel测试用例封装
    1.安装依赖pipinstallpytest-xlsx收集xlsx文件解析内容,识别测试用例将测试用例交给pytest框架参考文档:https://mp.weixin.qq.com/s/iD_KWamziFrTnDt8qpuWWA2.创建excel文件2.1基本例子注意点:文件名称:test_开头文件内容:必须有标记列插件在运行时,会解析【标记】这一......
  • 如何在C#中解析Excel公式
    前言在日常工作中,我们经常需要在Excel中使用公式对表中数据进行计算(求和、求差和求均值等)和分析,从而实现对数据的分类,通常情况下,当数据量较少或场景变化单一的情况下,使用公式可以满足用户的要求,但当数据量较大或者场景变化复杂的情况下,使用公式也无法满足用户的需求的情况。这个......
  • $b$2在excel引用,$a$1在excel引用的意思
    在Excel中,$B$2是一个单元格引用,$表示绝对引用。在自动填充时,带有$的单元格将保持不变。当我们在Excel中输入公式或函数时,可以使用单元格引用来实现对数据的计算和引用。在这个例子中,$B$2表示的是B列的第二行,也就是B2单元格。 $A$1表示第一行第一列的单元格,即A1单元格;$D$......