无法在ASP.Net中使用ExcelReader读取Excel工作表?

时间:2012-02-24 09:33:42

标签: c# asp.net excel

我使用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包含的数据包含整数,字符串,日期时间,超链接。谁能告诉我这可能是什么问题或替代方案? enter image description here

2 个答案:

答案 0 :(得分:0)

我正在使用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

答案 1 :(得分:0)

如果您正在上传文件,并且文件中有多张工作表,并且您想要阅读所有工作表,则可以使用此方法....首先编写Code for 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];
    } 

否则U可以使用此方法读取excel文件

只需添加参考 单击解决方案资源管理器上的“AddReference”,单击“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();
        }


    }

希望这可以帮助你..........如果你有任何疑问请问我......