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

标签 c# excel interop dataset excel-interop

我想做什么

我正在尝试使用 Microsoft.Office.Interop.Excel namespace打开 Excel 文件(XSL 或 CSV,但遗憾的是不是 XSLX)并将其导入数据集。我无法控制工作表或列名称,因此我需要允许对它们进行更改。

我尝试过的

我试过 OLEDB method这在过去,并且有很多问题(错误,缓慢,并且需要 Excel 文件架构的先验知识),所以我想避免再次这样做。我想做的是使用 Microsoft.Office.Interop.Excel 将工作簿直接导入数据集,或者循环遍历工作表并将每个工作表加载到数据表中。

信不信由你,我很难找到这方面的资源。 A few searches on StackOverflow发现大多数人试图做相反的事情(DataSet => Excel)或 OLEDB 技术。 Google 并没有提供更多帮助。

到目前为止我得到了什么

    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 Data Reader 怎么样? (以前主持 here)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();

更新

经过一番搜索,我发现了这篇文章:Faster MS Excel Reading using Office Interop Assemblies .本文仅使用 Office Interop Assemblies 从给定的 Excel 工作表中读取数据。该项目的源代码也在那里。我想这篇文章可以作为您想要实现的目标的起点。看看有没有帮助

更新 2

下面的代码采用 excel 工作簿 并读取在 excel 工作簿 中的每个 excel 工作表 中找到的所有值。

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 表示列。

关于c# - 如何使用 Microsoft.Office.Interop.Excel 从 Excel 导入数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7244971/

相关文章:

c# - 是什么决定了 WPF 中文本的修剪方式

c# - 有什么方法可以调用这个 getter 并始终如一地获得预期结果吗?

c# - Excel 单元格公式正在使用工作表名称更新。从 ASP.NET 导出

vba - Excel卡住太多行

.net - 在编码包装通过传递接口(interface)句柄工作的 C++ 接口(interface)(全部抽象)时 Intptr 是否足够?

python - Python中如何区分不同类型的NaN float

.net - 用 C 编写 .NET 对象?

c# - ASP.NET MVC 4 Code-First IdentityUserRole 与额外的主键三向关系

c# - 无法弄清楚如何使用以下方法计算非复合税和混合税?

excel - 使用 Excel,尝试从外部 HTA 中查找真正使用过的范围