首页 > 其他分享 >Npoi 中一个sheet多个 head row 情况下设置自动合适的宽度

Npoi 中一个sheet多个 head row 情况下设置自动合适的宽度

时间:2024-02-26 15:22:45浏览次数:25  
标签:head sheet int Npoi Add dics var new

    public void TEst()
    {
        var dics = new List<Dictionary<string, int>>();
        dics.Add(new Dictionary<string, int> { { "key0", 12 }, { "key1", 4 }, { "key2", 5 }, { "key3", 8 } });
        dics.Add(new Dictionary<string, int> { { "key0", 3 }, { "key1", 6 }, { "key2", 19 } });
        dics.Add(new Dictionary<string, int> { { "key0", 11 }, { "key1", 16 }, { "key2", 2 }, { "key3", 28 }, { "key4", 38 }, { "key5", 55 } });


        GetMaxWidthByDic(dics, 1);
    }
  /// <summary>
    /// get maxwidth
    /// </summary>
    /// <param name="dics"></param>
    /// <param name="inputColumnindex"></param>
    /// <returns></returns>
    private int GetMaxWidthByDic(List<Dictionary<string, int>> dics, int inputColumnindex)
    {
        var minLengthDics = new List<int>();
        int diclength = dics.Count;//dic 的数量
        for (int i = 0; i < dics.Count; i++)
        {
            minLengthDics.Add(dics[i].Count);
        }
        int minLengthDic = minLengthDics.Min();//最小Dic的key长度

        if (inputColumnindex > minLengthDic)
        {
            inputColumnindex = minLengthDic;//最大输入的值重新处理判断
        }
        int index = 0;
        for (int i2 = 0; i2 < dics.Count; i2++)
        {
            if (dics[i2].Count == minLengthDic)
            {
                index = i2;
                break;
            }
        }
        var newdic = new Dictionary<string, int>();

        for (int c = 0; c < dics[index].Count; c++)//最小的字典的那个长度
        {
            var MaxInt = new List<int>();
            for (int L = 0; L < diclength; L++)//dic数量
            {
                MaxInt.Add(dics[L]["key" + c]);
            }
            int maxV = MaxInt.Max();
            newdic.Add($"key{c}", maxV);
        }

        return newdic["key" + inputColumnindex];
        // foreach (var q in newdic.Keys)
        // {
        //     Console.WriteLine($"key:{q}--value:{newdic[q]}");
        // }
    }

    public async Task<byte[]> ExportReportQuotationByNpoiAsync(Guid quotationId, QuotationOutput _quotationResult)
    {
        //Quotation主要信息
        // var quotationResult =_quotationResult;// await _quotationconfigAppService.GetByIdAsync(quotationId);

        var quotationMainExportDtos = new List<QuotationMainExportDto>();
        var quotationAllInfo = _quotationResult;// quotationResult.Data;
        var quotationMainExportDto = ObjectMapper.Map<QuotationOutput, QuotationMainExportDto>(quotationAllInfo);
        quotationMainExportDtos.Add(quotationMainExportDto);

        var itemsProduct = quotationAllInfo.QuotationProductModels.ToList();
        var quotationSelctProductExportDto = ObjectMapper.Map<List<QuotationProductModelsOutput>, List<QuotationSelctProductExportDto>>(itemsProduct);

        //是否选中的yes赋值
        var choseProcessDic = new Dictionary<string, List<string>>();
        foreach (var item in itemsProduct)
        {
            var itemSelectPros = item.ProcessSectionOutputDtos.ToList().Where(c => c.IsChecked == true).Select(c => c.ProcessSectionName).ToList();
            choseProcessDic.Add(item.ModelPN ?? "keyno", itemSelectPros);
        }
        string processNameStr = ConnectionJsonDto.SmtWaveBackProcess ?? "SMT,Wave,Back";
        var processSectionName = processNameStr.Split(",");
        foreach (var qproduct in quotationSelctProductExportDto)
        {
            qproduct.SmtProcess = choseProcessDic[qproduct.modelPN].Any(c => c.Contains(processSectionName[0])) ? "YES" : "NO";
            qproduct.WaveProcess = choseProcessDic[qproduct.modelPN].Any(c => c.Contains(processSectionName[1])) ? "YES" : "NO";
            qproduct.BackendProcess = choseProcessDic[qproduct.modelPN].Any(c => c.Contains(processSectionName[2])) ? "YES" : "NO";
            qproduct.OtherProcess = "NO";
        }

        //quotationSelctProductExportDto
        var productIds = quotationAllInfo.QuotationProductModels.ToList().Select(c => c.ProductId).ToList();
        if (productIds == null || productIds.Count <= 0)
            throw new Exception("Please Chose Product First!");

        var listProduct = new List<QueryProductModelAllInfo>();
        foreach (var _productId in productIds)
        {
            //产品信息
            var productResult = await _productAppService.QueryOneProductModel(_productId);
            if (productResult.Data != null)
                listProduct.Add(productResult.Data);
        }
        IWorkbook wookbook = new XSSFWorkbook();
        ISheet sheet = wookbook.CreateSheet("Quotation");
        int rowIndex = 0;//第几行
        IRow headRow = sheet.CreateRow(rowIndex);
        headRow.Height = 350;
        ICellStyle cellStyleBgColor = wookbook.CreateCellStyle();
        // cellStyleBgColor.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.White.Index; //IndexedColors.Grey25Percent.Index;
        // cellStyleBgColor.FillPattern = FillPattern.SolidForeground;
        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;
        //Quotation
        var dicQuotation_tupe = DoRowCellWork_productInfos<QuotationMainExportDto>(rowIndex, sheet, cellStyleBgColor, quotationMainExportDtos);

        //product
        int product_rowIndex = quotationMainExportDtos.Count + 3;
        var dicQuotationProduct_tupe = DoRowCellWork_productInfos<QuotationSelctProductExportDto>(product_rowIndex, sheet, cellStyleBgColor, quotationSelctProductExportDto);

        var listDic = new List<Dictionary<string, int>>();
        listDic.Add(dicQuotation_tupe.Item2);
        listDic.Add(dicQuotationProduct_tupe.Item2);
    //参数一:同sheet中最小的哪一行 head ,参数二:当前的sheet即可,参数3:数据,如4个table的数据在一个sheet中 AutoSetExcelWidth(dicQuotationProduct_tupe.Item1, sheet, listDic);// TODO }
 private Tuple<IRow, Dictionary<string, int>> DoRowCellWork_productInfos<T>(int rowCount, ISheet sheet, ICellStyle cellStyleBgColor, List<T> datas)
    {
        var dic = new Dictionary<string, int>();
        int product_rowIndex = rowCount;
        PropertyInfo[] pts = typeof(T).GetProperties();
        // if (myorder) //orderbypropertity
        // {
        //     //order propertity
        //     pts = pts.Where(c => Attribute.IsDefined(c, typeof(DataMemberAttribute)))
        //     .OrderBy(c => ((DataMemberAttribute)Attribute.GetCustomAttribute(c, typeof(DataMemberAttribute))).Order).ToArray();
        // }

        IRow headRow_product = sheet.CreateRow(product_rowIndex);
        headRow_product.Height = 350;
        for (int i = 0; i < pts.Length; i++)
        {
            var qname = pts[i].GetCustomAttribute<QuotaNameAttribute>();
            if (qname != null)
            {
                ICell cell = headRow_product.CreateCell(i);
                // cell.SetCellValue(pts[i].Name);
                cell.SetCellValue(qname.DisplayName);
                cell.CellStyle = cellStyleBgColor;
                dic.Add($"key{i}", (Encoding.Default.GetBytes(cell.StringCellValue).Length * 256) + 500);//200
            }
        }
        for (int s = 0; s < datas.Count; s++)
        {
            product_rowIndex += 1;
            var row = sheet.CreateRow(product_rowIndex);
            for (int p = 0; p < pts.Length; p++)
            {
                string strV = pts[p].GetValue(datas[s] ?? default)?.ToString() ?? "";
                ICell cell = row.CreateCell(p);
                cell.SetCellValue(strV);
                int valuelength = Encoding.Default.GetBytes(cell.StringCellValue).Length * 256 + 500;
                valuelength = valuelength > 15000 ? 15000 : valuelength;
                if (dic[$"key{p}"] < valuelength)
                    dic[$"key{p}"] = valuelength;
            }
        }

        // TODO jason  20240221
        for (int i = 0; i < headRow_product.Cells.Count; i++)
        {
            sheet.SetColumnWidth(i, dic[$"key{i}"]);
        }
        return Tuple.Create(headRow_product, dic);// dic;
    }

 

标签:head,sheet,int,Npoi,Add,dics,var,new
From: https://www.cnblogs.com/Fengge518/p/18034330

相关文章

  • NavigableMap.headMap()的用法
    Java中NavigableMap接口的headMap()方法用于返回此Map的一部分,其键小于(或等于,如果包含,则为true)toKey的map NavigableMap<K,V>headMap(KtoKey,booleaninclusive)参数:此函数接受两个参数:toKey:此参数指的是key。inclusive:此参数决定是否......
  • Unity编辑器扩展秘籍-利用Editor.finishedDefaultHeaderGUI增加Header功能
    利用Editor.finishedDefaultHeaderGUI这个回调可以实现自定义Header菜单usingUnityEditor;usingUnityEngine;namespaceYaojz{[InitializeOnLoad]publicstaticclassDefaultHeaderDrawer{staticDefaultHeaderDrawer(){E......
  • 界面控件DevExpress Spreadsheet组件(v23.2)——增强的图表功能
    DevExpress拥有.NET开发需要的所有平台控件,包含600多个UI控件、报表平台、DevExpressDashboardeXpressApp框架、适用于VisualStudio的CodeRush等一系列辅助工具。在本文中,我将描述在DevExpress上一个主要版本(v23.2)中引入的WinForms和WPF电子表格图表API增强。获取DevExpr......
  • 界面控件DevExpress ASP.NET Spreadsheet组件 - 轻松集成电子表格功能!(二)
    DevExpressASP.NETSpreadsheet组件允许您轻松地将电子表格功能合并到任意ASP.NET应用程序,它可以加载、转换和保存工作簿到XLS-XLSx二进制文件格式,还可以导出和导入XLSX、CSV和TXT文件。在上文中(点击这里回顾>>),主要为大家介绍了DevExpressASP.NETSpreadsheet组件的Excel兼容......
  • C代码实践——《Head first C》C语言实验室2
    目录任务要求完成过程Step1.安装OpenCVStep2.配置环境变量Step3.配置编译环境Step4.编写程序代码Step5.测试运行调整反思、总结、收获最终程序代码任务要求入侵者检测器计算机用摄像头持续监测周围环境,当检测到有物体在移动时就会把当前捕捉到的图像保存为文件。完成过程Step......
  • bits/libc-header-start.h: No such file or directory
    问题出现在编译一个工程的时候,出现了报错Infileincludedfrom/usr/lib/gcc/x86_64-linux-gnu/9/include/stdint.h:9,frommain.c:1:/usr/includ......
  • [972] Remove specific sheets from an Excel file
    ToremovespecificsheetsfromanExcelfile,youcanusetheopenpyxllibraryinPython.Here'showyoucandoit:fromopenpyxlimportload_workbook#PathtotheExcelfileexcel_file_path='example.xlsx'#OpentheExcelworkbookwb......
  • [970] Combine multiple Excel files into one Excel file with multiple sheets
    YoucancombinemultipleExcelfilesintooneExcelfilewithmultiplesheetsusingthePandaslibraryinPython.Here'sageneralapproach:ReadeachExcelfileintoaPandasDataFrame.CreateanExcelwriterobjectusingPandas.WriteeachDataFra......
  • [971] [Keep original formats] Combine multiple Excel files into one Excel file w
    IftheexistingExcelfilehasspecialformattingthatpreventsreadingitdirectlywithPandas,youcanusealibrarylikeopenpyxltohandletheappendingofnewsheets.Here'showyoucanachievethis:importosfromopenpyxlimportload_workbook......
  • 一句话总结Kubernetes的Headless服务
    Kubernetes的概念很多,有的着实让人费解,比如说Headless服务,听名字就很拗口。那Headless服务是什么,使用场景是什么。一句话总结:Headless服务就是一组Pod组成的只供集群内访问(没有ClusterIP)的Service,一般结合StatefulSet用于部署有状态应用的场景。1、Service与服务发现提到Headl......