如何使用 Microsoft.Office.Interop.Excel 从 Excel 导入数据集?

2024-04-22

我想做的事

我正在尝试使用Microsoft.Office.Interop.Excel名称空间 http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel%28v=office.14%29.aspx打开 Excel 文件(XLS 或 CSV,但遗憾的是notXSLX)并将其导入到数据集中。我无法控制工作表或列名称,因此我需要允许对它们进行更改。

我尝试过的

我已经尝试过OLEDB方法 http://www.c-sharpcorner.com/uploadfile/yuanwang200409/102242008174401pm/1.aspx过去曾遇到过这种情况,并且遇到了很多问题(有问题、速度慢,并且需要先了解 Excel 文件的架构),所以我想避免再次这样做。我想要做的是使用 Microsoft.Office.Interop.Excel 将工作簿直接导入到数据集,或循环遍历工作表并将每个工作表加载到数据表中。

不管你相信与否,我很难找到这方面的资源。我们发现大多数人都试图做相反的事情(DataSet => Excel),或者 OLEDB 技术。谷歌并没有提供更多帮助。

到目前为止我所得到的

    public void Load(string filename, Excel.XlFileFormat format = Excel.XlFileFormat.xlCSV)
    {
        app = new Excel.Application();
        book = app.Workbooks.Open(Filename: filename, Format: format);

        DataSet ds = new DataSet();

        foreach (Excel.Worksheet sheet in book.Sheets)
        {
            DataTable dt = new DataTable(sheet.Name);
            ds.Tables.Add(dt);

            //??? Fill dt from sheet 
        }

        this.Data = ds;
    }

我可以一次导入整本书,也可以一次循环一页。我可以使用 Interop.Excel 执行此操作吗?


使用怎么样Excel 数据阅读器 https://github.com/ExcelDataReader/ExcelDataReader(之前主持过here http://exceldatareader.codeplex.com/)codeplex 上的开源项目?它非常适合我从 Excel 工作表导出数据。

指定链接上给出的示例代码:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

UPDATE

经过一番搜索,我发现了这篇文章:使用 Office Interop 程序集更快地读取 MS Excel http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=9992。文章仅使用Office Interop Assemblies从给定的 Excel 工作表中读取数据。该项目的源代码也在那里。我想这篇文章可以成为您想要实现的目标的起点。看看是否有帮助

UPDATE 2

下面的代码需要一个excel workbook并读取找到的所有值,对于每个excel worksheet在 - 的里面excel workbook.

private static void TestExcel()
    {
        ApplicationClass app = new ApplicationClass();
        Workbook book = null;
        Range range = null;

        try
        {
            app.Visible = false;
            app.ScreenUpdating = false;
            app.DisplayAlerts = false;

            string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

            book = app.Workbooks.Open(@"C:\data.xls", Missing.Value, Missing.Value, Missing.Value
                                              , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                             , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                            , Missing.Value, Missing.Value, Missing.Value);
            foreach (Worksheet sheet in book.Worksheets)
            {

                Console.WriteLine(@"Values for Sheet "+sheet.Index);

                // get a range to work with
                range = sheet.get_Range("A1", Missing.Value);
                // get the end of values to the right (will stop at the first empty cell)
                range = range.get_End(XlDirection.xlToRight);
                // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                range = range.get_End(XlDirection.xlDown);

                // get the address of the bottom, right cell
                string downAddress = range.get_Address(
                    false, false, XlReferenceStyle.xlA1,
                    Type.Missing, Type.Missing);

                // Get the range, then values from a1
                range = sheet.get_Range("A1", downAddress);
                object[,] values = (object[,]) range.Value2;

                // View the values
                Console.Write("\t");
                Console.WriteLine();
                for (int i = 1; i <= values.GetLength(0); i++)
                {
                    for (int j = 1; j <= values.GetLength(1); j++)
                    {
                        Console.Write("{0}\t", values[i, j]);
                    }
                    Console.WriteLine();
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            range = null;
            if (book != null)
                book.Close(false, Missing.Value, Missing.Value);
            book = null;
            if (app != null)
                app.Quit();
            app = null;
        }
    }

在上面的代码中,values[i, j]是您需要添加到的值dataset. i表示行,而j表示列。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Microsoft.Office.Interop.Excel 从 Excel 导入数据集? 的相关文章

随机推荐