2012-02-24 18 views
0

私は、次のコードを使用してExcelシートを読み取るために、読者に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には整数、文字列、日時、ハイパーリンクが含まれています。誰かが私にこのことのための問題か代替案を教えてくれますか? 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ファイルをアップロードすることはできますか? –

0

の両方で動作しますあなたはUが読み、このメソッドを使用することができます

エルス
/// <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はファイル

ただ、これがあなたの役に立てば幸い

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(); 
     } 


    } 

Microsoft.Office.Interop.Excel

、ソリューションエクスプローラの「AddReference」に参照に クリックを追加COM]タブをクリックし、この参照 を追加します...... .... uは疑問が...

関連する問題