【问题标题】:Unable to read excel sheet using ExcelReader in ASP.Net?无法在 ASP.Net 中使用 ExcelReader 读取 excel 表?
【发布时间】:2012-02-24 09:33:41
【问题描述】:

我正在使用 IExcelDataReader 阅读器使用以下代码读取 excel 表:

private static IExcelDataReader FetchDataReaderForExcel(HttpPostedFile file)
{
    IExcelDataReader dataReader = null;

    if (null != file)
    {
        string fileExtension = Path.GetExtension(file.FileName);

        switch (fileExtension)
        {
            case ".xls":
                dataReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream);
                break;
            case ".xlsx":
                dataReader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
                break;
            default:
                dataReader = null;
                break;
        }
    }

    return dataReader;
}

当我使用这种方法读取 excel 表时,有时我无法正确读取数据。有时它无法读取列,有时它无法读取整个数据。我需要将每列格式化为普通文本,然后再次上传,然后就可以了。 Excel 包含的数据包含整数、字符串、日期时间、超链接。谁能告诉我这可能是什么问题或替代方法?

【问题讨论】:

    标签: c# asp.net excel


    【解决方案1】:

    我正在使用 oledb,它非常适合我。这是我的例子:

        using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Filename + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\""))
        {
            //
            string listName = "Sheet1";
            con.Open();
            try
            {
                DataSet ds = new DataSet();
                OleDbDataAdapter odb = new OleDbDataAdapter("select * from [" + listName + "$]", con);
                odb.Fill(ds);
                con.Close();
                foreach (DataRow myrow in ds.Tables[0].Rows)
                {
    
                    Object[] cells = myrow.ItemArray;
                    if (cells[0].ToString().Length > 0 || cells[1].ToString().Length > 0 || cells[2].ToString().Length > 0)
                    {
                        /*
                        cells[0]
                        cells[1]
                        cells[2]
                        are getting values
                        */
    
                    }
                }
    
    
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    

    OLEDB.12.0 适用于 .xls 和 .xlsx

    【讨论】:

    • 我可以上传 Excel 文件,因为我们是一个网站,用户需要上传 Excel 表格,这可以在那里工作吗?
    【解决方案2】:

    如果您正在上传文件,并且文件中有很多工作表,并且您想阅读所有工作表,您可以按照此方法....首先编写 FileUPload 的代码并将上传的文件保存在一个路径中。 ...使用该路径,您可以读取文件

        /// <summary>
    
        /// This method retrieves the excel sheet names from 
    
        /// an excel workbook & reads the excel file
    
    
        /// </summary>
    
        /// <param name="excelFile">The excel file.</param>
    
        /// <returns></returns>
        #region GetsAllTheSheetNames of An Excel File
        public static string[] ExcelSheetNames(String excelFile)
        {
            DataTable dt;
            string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=Yes'";
    
            using (OleDbConnection objConn = new OleDbConnection(connString))
            {
                objConn.Open();
                dt =
                objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt == null)
                {
                    return null;
                }
                string[] res = new string[dt.Rows.Count];
                for (int i = 0; i < res.Length; i++)
                {
                    string name = dt.Rows[i]["TABLE_NAME"].ToString();
                    if (name[0] == '\'')
                    {
                        //numeric sheetnames get single quotes around
                        //remove them here
                        if (Regex.IsMatch(name, @"^'\d\w+\$'$"))
                        {
                            name = name.Substring(1, name.Length - 2);
                        }
                    }
                    res[i] = name;
                }
                return res;
            }
        }
        #endregion
    //You can read files and store the data in a dataset use them 
           public  static DataTable GetWorksheet(string excelFile,string worksheetName)
        {
            string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=Yes'";  
            OleDbConnection con = new System.Data.OleDb.OleDbConnection(connString);
            OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter("select * from [" + worksheetName + "$]", con);
    
            con.Open();
            System.Data.DataSet excelDataSet = new DataSet();
            cmd.Fill(excelDataSet);
            con.Close();
    
            return excelDataSet.Tables[0];
        } 
    

    其他的可以用这个方法读取excel文件

    只需添加参考 单击解决方案资源管理器上的“添加引用”,单击 com 选项卡并添加此引用 Microsoft.Office.Interop.Excel

        And add this namespace in your code behind
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using Excel = Microsoft.Office.Interop.Excel; 
        using System.IO;
        using System.Data; 
    
    
         static void Main(string[] args)
        {
            string Path = @"C:\samples\SEP DUMPS.xls";
            // initialize the Excel Application class
            Excel.Application app = new Excel.Application();           
            //Excel.Worksheet NwSheet;
            Excel.Range ShtRange;
            // create the workbook object by opening  the excel file.
            Excel.Workbook workBook = app.Workbooks.Open(Path,0,true,5,"","",true,Excel.XlPlatform.xlWindows,"\t",false,false, 0,true,1,0);
            // Get The Active Worksheet Using Sheet Name Or Active Sheet
            Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
            int index = 1;
            // that is which cell in the excel you are interesting to read.
            object rowIndex = 1;
            object colIndex1 = 1;
            object colIndex2 = 5;
            object colIndex3 = 4;
            System.Text.StringBuilder sb = new StringBuilder();
            try
            {
                while (((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
                {
                    rowIndex =index;
                    string firstName = Convert.ToString( ((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value2);
                    string lastName = Convert.ToString(((Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value2);
                    string Name = Convert.ToString(((Excel.Range)workSheet.Cells[rowIndex, colIndex3]).Value2);
                    string line = firstName + "," + lastName + "," + Name;
                    sb.Append(line); sb.Append(Environment.NewLine);
                    Console.WriteLine(" {0},{1},{2} ", firstName, lastName,Name);
                    index++;
                }
    
               Writetofile(sb.ToString());
    
                ShtRange = workSheet.UsedRange;
                Object[,] s = ShtRange.Value;            
    
    
            }
            catch (Exception ex)
            {
                app.Quit();
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
    
    
        }
    

    希望这对你有帮助............如果你有任何疑问,问我......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      相关资源
      最近更新 更多