在C#中读取.xlsx文件 [英] Reading .xlsx file in C#

查看:1302
本文介绍了在C#中读取.xlsx文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在c#中读取.xlsx表格,其内容分散在表格上。这不是一张桌子。请查看图片 http://i.stack.imgur.com/aaXxz.png [ ^ ]。



如果可能的话,我在dataTables中突出显示了我想单独阅读的内容。

我使用了以下代码,但只有当工作表中只有一个表时它才有效。





请帮忙。谢谢。



我的尝试:



I'm trying to read .xlsx sheet in c# whose contents are spread over sheet. It's not a single table.Please look at the image http://i.stack.imgur.com/aaXxz.png[^].

I've highlighted the things which I want to read separately, in dataTables , if possible.
I've used Following code but it only works when there is only one table is present in the sheet.


Please help. Thanks.

What I have tried:

public DataSet ReadXlsx(string filepath)
{
    try
    {
        FileStream stream = File.Open(filepath, FileMode.Open, FileAccess.Read);

        //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
        IExcelDataReader excelReader2 = ExcelReaderFactory.CreateOpenXmlReader(stream);

        //...
        //4. DataSet - Create column names from first row
        excelReader2.IsFirstRowAsColumnNames = true;
        DataSet result2 = excelReader2.AsDataSet();

        return result2;
    }
    catch (Exception ex)
    {

        return null;
    }
}

推荐答案

您可以从exceldatareader.codeplex.com获取代码。如果你得到那个组件并希望完成基于该组件的代码,你可以继续这样:



你现在有了你的DataSet,所以继续阅读它就像你一样数据库结果:



You get your code from exceldatareader.codeplex.com. if you get that component and want to complete your code based on that component you can continue like this:

You have your DataSet now, so continue reading it as you do with database results:

            DataSet ds= ReadXlsx(filepath);

            string theOrder = ds.Tables[0].Rows[0][0].ToString();
            string theSite = ds.Tables[0].Rows[2][0].ToString();
            List<job> jobs= new List<job>();
            for (int i = 4; i < ds.Tables[0].Rows.Count; i++)
            {
                Job job=new Job();
                job.Number = ds.Tables[0].Rows[i][0];
                job.Facility = ds.Tables[0].Rows[i][1].ToString();
                job.Date = ds.Tables[0].Rows[i][2];
                job.TrackingNumber = ds.Tables[0].Rows[i][3];
                jobs.Add(job);
            }

</job></job>





我还建议您使用具有强大功能的EPPlus。

你可以通过NuGet下载它:



https://www.nuget.org/packages/EPPlus [ ^ ]



在此了解更多信息:

使用EPPlus在C#.Net中创建/读取/编辑高级Excel 2007/2010报告 [ ^ ]


这篇关于在C#中读取.xlsx文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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