C#EPPlus从Excel工作表中删除行 [英] C# EPPlus delete row from excel sheet

查看:245
本文介绍了C#EPPlus从Excel工作表中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用一个Excel文件,该文件的前几行包含不需要的信息。这些多余的行也将数据导入下面的标题行中。因此,我正在尝试删除它们以处理数据。

 使用(var pack = new ExcelPackage(myFileInfo))
{
//应该返回工作表名称
var ws = pack.Workbook.Worksheets.FirstOrDefault();
//应该删除第1-5行,并在删除后向上移动
ws.DeleteRow(1,5,true);
}

我在想类似上面的方法可以工作,但我没有取得了很大的成功。



目标是删除1-5行,上移其余数据(也许可以合并?),然后将其转换为数据表。



任何人都有技巧或资源来从我的excel工作表中删除行(在将其移入数据表之前,因为这是问题所在)

解决方案

您所拥有的代码将删除前5行,但是您还需要对修改后的文件做一些事情。您可以使用以下方式将其保存到位:

  pack.Save(); 

或使用以下方式保存到新位置:

  pack.SaveAs(new FileInfo(outputFilePath)); 

我上载了完整的示例



为此在输出文件中:





删除了前5行,并且所有内容都向上移动了。


I'm currently working with an Excel file that has leading rows that have information I don't need. These extra rows also mess with importing that data in the header row below. So I'm trying to remove them to work with the data.

using (var pack = new ExcelPackage(myFileInfo))
{
    // Should return the sheet name
    var ws = pack.Workbook.Worksheets.FirstOrDefault();
    // Should Delete rows 1-5 and shift up the rows after deletion
    ws.DeleteRow(1,5,true);
}

I was thinking something like the above would work, but I've not had much success with it.

The goal would be to delete rows 1-5, shift up the rest of the data (maybe a merge would work?) then convert it into a datatable.

Anyone have tips tips or resources on removing rows from my excel sheet (prior to moving it into a datatable since that is where the issue occurs)

解决方案

The code as you have it will remove the first 5 rows but you also need to do something with the amended file. You could save it in place with:

pack.Save();

or save to a new location with:

pack.SaveAs(new FileInfo(outputFilePath));

I have uploaded a complete example here:

static void Main(string[] args)
{
    var myFileInfo = new FileInfo("Demo.xlsx");
    using (var pack = new ExcelPackage(myFileInfo))
    {
        var ws = pack.Workbook.Worksheets.FirstOrDefault();
        ws.DeleteRow(1, 5, true);
        pack.SaveAs(new FileInfo("output.xlsx"));
    }
}

If you build and run the solution you can see that it transforms the demo file from this in the input file (Demo.xlsx):

to this in the output file:

with the first 5 rows removed and everything shifted up.

这篇关于C#EPPlus从Excel工作表中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆