【问题标题】:Importing excel files in c#在c#中导入excel文件
【发布时间】:2012-01-13 23:25:37
【问题描述】:

谁能建议我如何在断开模式下使用 ado.net 在 c# 中读取 excel 文件。我的 excel 文件很大,无法保存在内存中。请建议一种将数据加载到数据集中的方法。 现在我正在阅读它们,方法是使用 Excel = Microsoft.Office.Interop.Excel 并添加 excel 参考(com),然后使用范围等对象。

【问题讨论】:

  • 如果您告诉我们您现在是如何阅读它们的(什么图书馆等),将会有所帮助。

标签: c#


【解决方案1】:

也许这就是你要找的 http://exceldatareader.codeplex.com/

【讨论】:

  • 我无法让 OleDb 方法在 Windows7 上运行,但这就像一个魅力。谢谢。
【解决方案2】:

我说使用 ADO 连接它并将其视为数据库: http://www.connectionstrings.com/excel

【讨论】:

    【解决方案3】:

    这是我正在使用的示例,对于其他想要从 Excel 电子表格获取数据的人来说可能会很方便。

    • 它将每个工作表加载到DataSet 内的DataTable 中。
    • 假设您的标题从 A1 变为 x1。

    using System;  
    using System.Data;  
    using System.IO;  
    using System.Runtime.InteropServices;  
    using Excel = Microsoft.Office.Interop.Excel; 
    
    public class clsExcelWriter : IDisposable  
    {  
        private Excel.Application oExcel;  
        private Excel._Workbook oBook;  
        private Excel._Worksheet oSheet;  
    
        // Used to store the name of the current file
        public string FileName
        {
            get;
            private set;
        }
    
        public clsExcelWriter(string filename)
        {
            // Initialize Excel
            oExcel = new Excel.Application();
    
            if (!File.Exists(filename))
            {
                // Create a new one?
            }
            else
            {
                oBook = (Excel._Workbook)oExcel.Workbooks.Open(filename);
                oSheet = (Excel._Worksheet)oBook.ActiveSheet;
            }
    
            this.FileName = filename;
    
            // Supress any alerts
            oExcel.DisplayAlerts = false;
        }
    
    
        private string GetExcelColumnName(int columnNumber)
        {
            int dividend = columnNumber;
            string columnName = String.Empty;
            int modulo;
    
            while (dividend > 0)
            {
                modulo = (dividend - 1) % 26;
                columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
                dividend = (int)((dividend - modulo) / 26);
            }
            return columnName;
        }
    
        public void Dispose()
        {
            // Lets make sure we release those COM objects!
            if (oExcel != null)
            {
                Marshal.FinalReleaseComObject(oSheet);
                oBook.Close();
                Marshal.FinalReleaseComObject(oBook);
                oExcel.Quit();
                Marshal.FinalReleaseComObject(oExcel);
    
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    
    
        public static DataSet OpenFile(string filename)
        {
            DataSet ds = new DataSet();
            using (clsExcelWriter xl = new clsExcelWriter(filename))
            {
                // Iterate through each worksheet
                foreach (Excel._Worksheet sheet in xl.oBook.Worksheets)
                {
                    // Create a new table using the sheets name
                    DataTable dt = new DataTable(sheet.Name);
    
                    // Get the first row (where the headers should be located)
                    object[,] xlValues = (object[,])sheet.get_Range("A1", xl.GetExcelColumnName(sheet.UsedRange.Columns.Count) + 1).Value;
    
                    // Iterate through the values to add new DataColumns to the DataTable
                    for (int i = 0; i < xlValues.GetLength(1); i++)
                    {
                        dt.Columns.Add(new DataColumn(xlValues[1, i + 1].ToString()));
                    }
    
                    // Now get the rest of the rows
                    xlValues = (object[,])sheet.get_Range("A2", xl.GetExcelColumnName(sheet.UsedRange.Columns.Count) + sheet.UsedRange.Rows.Count).Value;
    
                    for (int row = 0; row < xlValues.GetLength(0); row++)
                    {
                        DataRow dr = dt.NewRow();
    
                        for (int col = 0; col < xlValues.GetLength(1); col++)
                        {
                            // xlValues array starts from 1, NOT 0 (just to confuse yee)
                            dr[dt.Columns[col].ColumnName] = xlValues[row + 1, col + 1];
                        }
                        dt.Rows.Add(dr);
                    }
                    ds.Tables.Add(dt);
                }
            }
            // Your DataSet should now be filled! :)
            return ds;
        }
    }
    

    }

    用法

    using System.Data;  
    using ExcelWriter;
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                DataSet ds = clsExcelWriter.OpenFile(@"C:\Results.xls");
    
                // Do some fancy stuff with the DataSet! xD
    
                while (true) ;
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      这是我用来从 Excel 工作表中读取数据的方法:

      private DbDataReader ReadExcelSheet(string file, string sheet)
              {
                  string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties=Excel 8.0;";
                  DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
                  DbConnection connection = factory.CreateConnection();
                  connection.ConnectionString = connStr;
                  DbCommand command = connection.CreateCommand();
      
                  string query = BuildSelectQuery(sheet, names_mapping);//you need column names here
      
                  command.CommandText = query;
                  connection.Open();
                  DbDataReader dr = command.ExecuteReader();
                  return dr;
              }
      

      【讨论】:

        猜你喜欢
        • 2019-02-18
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        • 2015-11-24
        • 1970-01-01
        • 2011-05-19
        • 2023-01-23
        • 2015-10-11
        相关资源
        最近更新 更多