首页 > 其他分享 >使用Npoi简单生成Excel并赋值导出小案例

使用Npoi简单生成Excel并赋值导出小案例

时间:2024-03-05 15:00:25浏览次数:11  
标签:cellStyle int Excel CellStyle modelCount CreateCell Npoi 赋值 cellStyleBgColor

 public async Task<byte[]> ExportNewReportByQuotationId(Guid quotationId)
    {
        IWorkbook wookbook = new XSSFWorkbook();
        //Engineer Quote Sheet
        await DoEngineerQuoteWork(wookbook, quotationId);

        //IL Sheet
        await DoILSheetWork(wookbook, quotationId);

        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 async Task DoILSheetWork(IWorkbook wookbook, Guid quotationId)
    {

        ISheet sheet = wookbook.CreateSheet("IL");
        var listProductPns = await GetQuotationProductNames(quotationId);
        int modelCount = listProductPns.Count;
        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;
        cellStyleBgColor.FillForegroundColor = HSSFColor.Grey25Percent.Index;
        cellStyleBgColor.FillPattern = FillPattern.SolidForeground;
        IFont font = wookbook.CreateFont();
        font.IsBold = true;
        font.FontHeightInPoints = 12;
        cellStyleBgColor.SetFont(font);
        ICellStyle cellStyle = wookbook.CreateCellStyle();
        cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        ICell cellhead1 = headRow1.CreateCell(0);
        cellhead1.SetCellValue("");
        cellhead1.CellStyle = cellStyle;
        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
        }
        int wlong = Encoding.UTF8.GetBytes("HC Required(HC Qty)").Length;
        int woneModelWidth = modelCount <= 1 ? (wlong * 256 + 260) : (wlong * 256 / 2 + 260);
        for (int mw = 0; mw < modelCount; mw++)
        {
            int mwIndex = mw + 1;
            sheet.SetColumnWidth(mwIndex, woneModelWidth);
        }
        ICell cellhead_b2 = headRow1.CreateCell(modelCount + 1);
        cellhead_b2.SetCellValue("Rate");
        cellhead_b2.CellStyle = cellStyleBgColor;
        if (modelCount > 1)
        {
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 1, modelCount));
        }

        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));

        var datas = await (await _QuotationExportExcelRepostory.GetQueryableAsync()).Where(c => c.QuoTationId == quotationId && c.ExcelType == 0).FirstOrDefaultAsync();
        string jsonStr = datas?.JsonData ?? "";
        AssmblyExcelModel(jsonStr, modelCount, sheet, cellStyle);
    }
 private void AssmblyExcelModel(string jsonStr, int modelCount, ISheet sheet, ICellStyle cellStyle)
    {
        //到时可以配置出去
        var templateStr = ConnectionJsonDto.ExportILLeftNames.Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();
        var ModelDatas = JsonConvert.DeserializeObject<List<ExcelILModelDto>>(jsonStr);
        for (int R = 0; R < templateStr.Count; R++)
        {
            int dataRow = R + 2;
            IRow row = sheet.CreateRow(dataRow);
            row.Height = 350;
            ICell cell = row.CreateCell(0);
            cell.SetCellValue(templateStr[R]);
            cell.CellStyle = cellStyle;

            for (int p = 0; p < modelCount; p++)
            {
                int pmodelIndex = p + 1;
                ICell cell2 = row.CreateCell(pmodelIndex);
                string nowValue = ModelDatas?.Where(c => c.RIndex == R && c.CIndex == pmodelIndex).FirstOrDefault()?.IV ?? "";
                cell2.SetCellValue(nowValue);
                cell2.CellStyle = cellStyle;
            }
            int b2Index = modelCount + 1;
            ICell cell_back2 = row.CreateCell(b2Index);
            string nowValue_b2 = ModelDatas?.Where(c => c.RIndex == R && c.CIndex == b2Index).FirstOrDefault()?.IV ?? "";
            cell_back2.SetCellValue(nowValue_b2);
            cell_back2.CellStyle = cellStyle;

            int b1Index = modelCount + 2;
            ICell cell_back1 = row.CreateCell(b1Index);
            string nowValue_b1 = ModelDatas?.Where(c => c.RIndex == R && c.CIndex == b1Index).FirstOrDefault()?.IV ?? "";
            cell_back1.SetCellValue(nowValue_b1);
            cell_back1.CellStyle = cellStyle;
        }
    }
 [HttpGet("ReportNewQuotation/{QuotationId}")]
    public async Task<ActionResult> ExportNewReportByQuotationId(Guid QuotationId)
    {
        try
        {
            //Quotation主要信息
            var quotationResult = await _quotationconfigAppService.GetByIdAsync(QuotationId);
            if (quotationResult.Data == null || string.IsNullOrEmpty(quotationResult.Data.RfqNo))
                throw new Exception("This Quotation donnot have RfqNo !");
            var by = await _exportReportAppService.ExportNewReportByQuotationId(QuotationId);
            return File(by, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Quotation_{quotationResult.Data.RfqNo}.xlsx");
        }
        catch (System.Exception ex)
        {
            _loggerService.LogError(ex.Message);
            return Json(new ResponseResult { Code = Jabil.Service.Extension.Customs.Enum.ResultCode.Error, Msg = "error" });
        }
    }

 

标签:cellStyle,int,Excel,CellStyle,modelCount,CreateCell,Npoi,赋值,cellStyleBgColor
From: https://www.cnblogs.com/Fengge518/p/18054067

相关文章

  • 导入Excel文件的时候公式为【#Ref!】应该怎么解决?
    前言在我们使用Excel时,经常会遇到一个问题,就是导入Excel时公式显示为【#Ref!】的情况。这通常是因为公式中引用的单元格已被删除或对应的工作表被删除,导致原公式无法识别对应的参数而显示为【#Ref!】。比如在一张Excel表中,sheet1中A1单元格的公式为‘=Sheet2!B1’,如果Sheet2......
  • .net core 6.0后台 Vue2前台 导出Excel文件
    要导出这样一个Excel表格:1.后端API下载安装包:EPPlus2.后端代码点击查看代码///<summary>///接口///</summary>///<returns>结果</returns>[HttpGet]publicIActionResultExportTab(){varli......
  • pytnon -- 解决在excel使用pyxll-jupyter时读取excel文件出现”OSError: [Errno 22] I
     在jupyter中运行以下代码:importpandasaspddataset=pd.read_excel(r'‪D:\a.xlsx',sheet_name='Sheet1')print(dataset)出现报错信息:---------------------------------------------------------------------------OSError......
  • 使用 Java 在Excel中创建下拉列表
    下拉列表(下拉框)可以确保用户仅从预先给定的选项中进行选择,这样不仅能减少数据输入错误,还能节省时间提高效率。在MSExcel中,我们可以通过“数据验证”提供的选项来创建下拉列表,但如果要在Java程序中通过代码实现这一功能,可能需要借助一些第三方库。本文将分享两种使用免费Java库......
  • 如何在 C# 中以编程的方式将 CSV 转为 Excel XLSX 文件
    前言MicrosoftExcel的XLSX格式以及基于文本的CSV(逗号分隔值)格式,是数据交换中常见的文件格式。应用程序通过实现对这些格式的读写支持,可以显著提升性能。在本文中,小编将为大家介绍如何在Java中以编程的方式将【比特币-美元】市场数据CSV文件转化为XLSX文件。具体操作步骤如下:......
  • C++ 赋值运算符'='重载
    C++拷贝构造函数(初学有点难理解)就像其他运算符一样,可以重载赋值运算符(=),用于创建一个对象,比如拷贝构造函数。1#include<iostream>2usingnamespacestd;3classDistance4{5private:6intfeet;//0到无穷7intinches;......
  • Npoi操作Excel单元格合并
    publicasyncTask<byte[]>ExportNewReportByQuotationId(GuidquotationId){//stringsql=@$"select""Id""asModelId,(q.qq).keyaskey,(q.qq).valueasmyValuefrom(withaas(select""Id"&q......
  • 前端 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......