简体   繁体   English

如何从epplus中的Excel工作表中删除列

[英]How to remove a column from excel sheet in epplus

I'm using csharp to insert data into excel sheet into 7 columns. 我正在使用csharp将数据插入到Excel列中的7列中。 The interface of this program will allow users to select 7 checkboxes. 该程序的界面将允许用户选择7个复选框。 If they select all 7, all the 7 columns in spreadhseet will have data, if they select one checkbox then only one column will have data. 如果他们选择全部7,则spreadhseet中的所有7列都将具有数据,如果他们选择一个复选框,则只有一列将具有数据。 I have got a for loop which will check if data is there, if no data exists, I want to remove that column in epplus. 我有一个for循环,它将检查数据是否存在,如果没有数据,我想删除epplus中的该列。 Here's a previous discussion on this topic How can I delete a Column of XLSX file with EPPlus in web app It's quiet old so I just wanna check if there's a way to do this. 以下是关于此主题的先前讨论如何在Web应用程序中删除带有EPPlus的XLSX文件列这是安静的,所以我只想检查是否有办法执行此操作。 Or, is there a way to cast epplus excel sheet to microsoft interop excel sheet and perform some operations. 或者,有没有办法将epplus excel表格转换为microsoft interop excel表格并执行一些操作。

Currently, I've code like this: 目前,我的代码如下:

for(int j=1; j <= 9; j++) //looping through columns
{
int flag = 0;
for(int i = 3; i <= 10; i++) // looping through rows
{
    if(worksheet.cells[i, j].Text != "")
    {
        flag ++;
    }
}
if (flag == 0)
{
     worksheet.column[j].hidden = true; // hiding the columns- want to  remove it
}
}

Can we do something like: 我们可以这样做:

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp = worksheet; (where worksheet is epplus worksheet)

Are you using EPPlus 4? 你在使用EPPlus 4吗? The ability to do column inserts and deletion was added with the new Cell store model they implemented. 使用他们实现的新Cell商店模型添加了执行列插入和删除的功能。 So you can now do something like this: 所以你现在可以这样做:

[TestMethod]
public void DeleteColumn_Test()
{
    //http://stackoverflow.com/questions/28359165/how-to-remove-a-column-from-excel-sheet-in-epplus

    var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
    if (existingFile.Exists)
        existingFile.Delete();

    //Throw in some data
    var datatable = new DataTable("tblData");
    datatable.Columns.Add(new DataColumn("Col1"));
    datatable.Columns.Add(new DataColumn("Col2"));
    datatable.Columns.Add(new DataColumn("Col3"));

    for (var i = 0; i < 20; i++)
    {
        var row = datatable.NewRow();
        row["Col1"] = "Col1 Row" + i;
        row["Col2"] = "Col2 Row" + i;
        row["Col3"] = "Col3 Row" + i;
        datatable.Rows.Add(row);
    }

    using (var pack = new ExcelPackage(existingFile))
    {

        var ws = pack.Workbook.Worksheets.Add("Content");
        ws.Cells.LoadFromDataTable(datatable, true);
        ws.DeleteColumn(2);

        pack.SaveAs(existingFile);
    }
}

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

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