简体   繁体   English

创建Excel时如何在EPPLUS库的Excel工作表中添加相同的列名

[英]How to add same column name in excel sheet in EPPLUS library while creating excel

I am using EPPLUS library for creating excel file with a data table. 我正在使用EPPLUS库来创建具有数据表的excel文件。 I have such column in my stored procedure: emp_name, sales, INR, marketing, INR But in excel file it generates column name like with column name like emp_name, sales, INR, marketing, INR1 etc. How do I prevent that to print whatever column name in the data table or any other configurations that I am missing? 我的存储过程中有这样的列:emp_name,sales,INR,marketing,INR,但是在excel文件中,它会生成列名,例如emp_name,sales,INR,marketing,INR1等列名。如何防止打印任何内容数据表中的列名称或其他缺少的配置?

Code: 码:

        string BasePath = ConfigurationManager.AppSettings["BasePath"];
        string fileName = Guid.NewGuid().ToString() + ".xlsx";
        string FilePath = BasePath + fileName;

        using (ExcelPackage excel = new ExcelPackage())
        {
            ExcelWorksheet ws = 
            excel.Workbook.Worksheets.Add("WorkingReport");

            ws.Cells["A1"].LoadFromDataTable(data,false);
            ws.Row(1).Style.Font.Bold = true;

            ws.Column(1).Width = 10;
            ws.Column(2).Width = 20;
            ws.Column(3).Width = 20;
            ws.Column(4).Width = 20;

            FileInfo excelFile = new FileInfo(FilePath);
            ws.Protection.IsProtected = false;
            excel.SaveAs(excelFile);
         }

INR and INR1 is printed because your datatable has those columns. 因为您的数据表中有这些列,所以会打印INR和INR1。 When same column is selected more than one time in a select list, SQL automatically aliases the column name by adding number at its end to distinguish between two columns. 当在选择列表中多次选择同一列时,SQL会通过在列名的末尾添加数字来区分两个列,从而自动为列名加上别名。 A datatable cannot have duplicate column names. 数据表不能具有重复的列名。 In your case, second INR is being renamed to INR1. 在您的情况下,第二个INR被重命名为INR1。 You could try 你可以试试

ws.Cells["A1"].LoadFromDataTable(data,true); //"PrintHeaders" true instead of false

but I think you will get the same result. 但我认为您会得到相同的结果。

If you can somehow manage to get cell address of header after data is loaded you can over write the value as ws.Cells["A5"].Value="INR" will overwrite the "INR1". 如果在加载数据后能够以某种方式设法获取标头的单元格地址,则可以将值ws.Cells["A5"].Value="INR"ws.Cells["A5"].Value="INR"将覆盖“ INR1”。 There are other ways also https://github.com/JanKallman/EPPlus/wiki/Addressing-a-worksheet 还有其他方法https://github.com/JanKallman/EPPlus/wiki/Addressing-a-worksheet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM