2012-02-24 43 views
0

我使用IExcelDataReader到讀取器讀取使用以下代碼excel表:無法讀取在ASP.Net使用ExcelReader 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

回答

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

+0

我可以上傳Excel文件,因爲我們是一個網站,用戶需要上傳有Excel工作表將這項工作呢? – 2012-02-24 14:13:14

0

如果您要上傳的文件,該文件中有許多表和你想讀的所有工作表你可以按照這個方法....先寫了文件上傳的代碼並保存在一個路徑上傳文件....使用路徑,你可以閱讀

/// <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文件

只需添加引用 點擊在Solution Explorer中的「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(); 
     } 


    } 

希望這有助於你...... ....如果妳有任何疑問,向我...