2009-03-18 141 views
58

Cách đọc tệp Excel bằng C#? Tôi mở một tập tin Excel để đọc và sao chép nó vào clipboard để tìm kiếm định dạng email, nhưng tôi không biết làm thế nào để làm điều đó.Cách đọc dữ liệu của tệp Excel bằng C#?

FileInfo finfo; 
Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass(); 
ExcelObj.Visible = false; 

Excel.Workbook theWorkbook; 
Excel.Worksheet worksheet; 

if (listView1.Items.Count > 0) 
{ 
    foreach (ListViewItem s in listView1.Items) 
    { 
     finfo = new FileInfo(s.Text); 
     if (finfo.Extension == ".xls" || finfo.Extension == ".xlsx" || finfo.Extension == ".xlt" || finfo.Extension == ".xlsm" || finfo.Extension == ".csv") 
     { 
      theWorkbook = ExcelObj.Workbooks.Open(s.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false); 

      for (int count = 1; count <= theWorkbook.Sheets.Count; count++) 
      { 
       worksheet = (Excel.Worksheet)theWorkbook.Worksheets.get_Item(count); 
       worksheet.Activate(); 
       worksheet.Visible = false; 
       worksheet.UsedRange.Cells.Select(); 
      } 
     } 
    } 
} 
+0

Người dùng mới sắp tới giải pháp có thể muốn xem [thread] này (https://stackoverflow.com/questions/33302235/how-to-read-from-xlsx-excel). –

Trả lời

17

Tại sao bạn không tạo OleDbConnection? Có rất nhiều tài nguyên có sẵn trên Internet. Dưới đây là một ví dụ

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filename+";Extended Properties=Excel 8.0"); 
con.Open(); 
try 
{ 
    //Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference 
    DataSet myDataSet = new DataSet(); 
    OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM ["+listname+"$]" , con); 
    myCommand.Fill(myDataSet); 
    con.Close(); 
    richTextBox1.AppendText("\nDataSet Filled"); 

    //Travers through each row in the dataset 
    foreach (DataRow myDataRow in myDataSet.Tables[0].Rows) 
    { 
      //Stores info in Datarow into an array 
      Object[] cells = myDataRow.ItemArray; 
      //Traverse through each array and put into object cellContent as type Object 
      //Using Object as for some reason the Dataset reads some blank value which 
      //causes a hissy fit when trying to read. By using object I can convert to 
      //String at a later point. 
      foreach (object cellContent in cells) 
      { 
       //Convert object cellContect into String to read whilst replacing Line Breaks with a defined character 
       string cellText = cellContent.ToString(); 
       cellText = cellText.Replace("\n", "|"); 
       //Read the string and put into Array of characters chars 
       richTextBox1.AppendText("\n"+cellText); 
      } 
    } 
    //Thread.Sleep(15000); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.ToString()); 
    //Thread.Sleep(15000); 
} 
finally 
{ 
    con.Close(); 
} 
+7

Liên kết đã qua đời –

+2

Một vấn đề tôi gặp phải với OleDbConnection (sử dụng Bộ điều hợp Dữ liệu Oracle) là một cột chứa cả số và văn bản. Tôi đã nhận một DataTable với cột được định dạng là số bị thiếu tất cả các ô nơi dữ liệu được định dạng dưới dạng văn bản. Giải pháp của tôi là sử dụng interop để chuyển đổi toàn bộ phạm vi được sử dụng của cột sang định dạng TEXT trước khi sử dụng OleDBC để lấy dữ liệu. –

+0

Lưu trữ lưu trữ cuối cùng [tại đây] (https://web.archive.org/web/20130731065653/http://blog.brezovsky.net/en-text-38.html). Chỉ có 40 dòng .. có lẽ chỉ cần chỉnh sửa bài đăng và thêm chúng vào. * Nhún vai * – Quantic

84

OK,

Một trong những khái niệm khó khăn hơn để nắm bắt về lập trình Excel VSTO là bạn không đề cập đến các tế bào giống như một mảng, Worksheet[0][0] sẽ không cung cấp cho bạn cell A1 , nó sẽ gây lỗi cho bạn. Ngay cả khi bạn gõ vào A1 khi Excel đang mở, bạn đang thực sự nhập dữ liệu vào Phạm vi A1. Do đó, bạn tham khảo ô như Phạm vi có tên. Dưới đây là một ví dụ:

Excel.Worksheet sheet = workbook.Sheets["Sheet1"] as Excel.Worksheet; 
Excel.Range range = sheet.get_Range("A1", Missing.Value) 

Bạn bây giờ có thể theo nghĩa đen gõ:

range.Text // this will give you the text the user sees 
range.Value2 // this will give you the actual value stored by Excel (without rounding) 

Nếu bạn muốn làm một cái gì đó như thế này:

Excel.Range range = sheet.get_Range("A1:A5", Missing.Value) 

if (range1 != null) 
    foreach (Excel.Range r in range1) 
    { 
     string user = r.Text 
     string value = r.Value2 

    } 

Có thể có một cách tốt hơn, nhưng điều này có đã làm cho tôi.

Lý do bạn cần sử dụng Value2 và không Value là do thuộc tính Value là một tham số và C# chưa hỗ trợ chúng.

Đối với mã dọn dẹp, tôi sẽ đăng bài đó khi tôi đi làm vào ngày mai, tôi không có mã với tôi, nhưng nó rất sôi nổi. Bạn chỉ cần đóng và giải phóng các đối tượng theo thứ tự ngược lại bạn đã tạo chúng. Bạn không thể sử dụng khối Using() vì Excel.Application hoặc Excel.Workbook không triển khai IDisposable và nếu bạn không dọn dẹp, bạn sẽ bị bỏ lại với một đối tượng Excel treo trong bộ nhớ.

Lưu ý:

  • Nếu bạn không thiết lập các tài sản Visibility Excel không hiển thị, có thể được ngạc cho người dùng của bạn, nhưng nếu bạn muốn chỉ cần trích xuất dữ liệu ra, đó có lẽ là tốt đủ
  • Bạn có thể OleDb, điều đó cũng sẽ hoạt động.

Tôi hy vọng bạn sẽ bắt đầu, hãy cho tôi biết nếu bạn cần làm rõ thêm. Tôi sẽ đăng một hoàn

đây là một ví dụ hoàn chỉnh:

using System; 
using System.IO; 
using System.Reflection; 
using NUnit.Framework; 
using ExcelTools = Ms.Office; 
using Excel = Microsoft.Office.Interop.Excel; 

namespace Tests 
{ 
    [TestFixture] 
    public class ExcelSingle 
    { 
     [Test] 
     public void ProcessWorkbook() 
     { 
      string file = @"C:\Users\Chris\Desktop\TestSheet.xls"; 
      Console.WriteLine(file); 

      Excel.Application excel = null; 
      Excel.Workbook wkb = null; 

      try 
      { 
       excel = new Excel.Application(); 

       wkb = ExcelTools.OfficeUtil.OpenBook(excel, file); 

       Excel.Worksheet sheet = wkb.Sheets["Data"] as Excel.Worksheet; 

       Excel.Range range = null; 

       if (sheet != null) 
        range = sheet.get_Range("A1", Missing.Value); 

       string A1 = String.Empty; 

       if(range != null) 
        A1 = range.Text.ToString(); 

       Console.WriteLine("A1 value: {0}", A1); 

      } 
      catch(Exception ex) 
      { 
       //if you need to handle stuff 
       Console.WriteLine(ex.Message); 
      } 
      finally 
      { 
       if (wkb != null) 
        ExcelTools.OfficeUtil.ReleaseRCM(wkb); 

       if (excel != null) 
        ExcelTools.OfficeUtil.ReleaseRCM(excel); 
      } 
     } 
    } 
} 

tôi sẽ đăng các chức năng từ ExcelTools ngày mai, tôi không có mã đó với tôi cả.

Chỉnh sửa: Như đã hứa, dưới đây là các hàm từ ExcelTools bạn có thể cần.

public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly, bool editable, 
     bool updateLinks) { 
     Excel.Workbook book = excelInstance.Workbooks.Open(
      fileName, updateLinks, readOnly, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing); 
     return book; 
    } 

public static void ReleaseRCM(object o) { 
     try { 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(o); 
     } catch { 
     } finally { 
      o = null; 
     } 
    } 

Nói thẳng ra, công cụ này dễ dàng hơn nhiều nếu bạn sử dụng VB.NET. Đó là trong C# bởi vì tôi đã không viết nó. VB.NET có các tham số tùy chọn tốt, C# không, do đó Type.Missing. Khi bạn đã nhập Loại.Bỏ lỡ hai lần liên tiếp, bạn chạy la hét từ phòng!

Đối với bạn thắc mắc, bạn có thể thử như sau:

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.find(VS.80).aspx

tôi sẽ đăng một ví dụ khi tôi nhận được trở lại từ cuộc họp của tôi ... chúc mừng

Edit: Đây là một ví dụ

range = sheet.Cells.Find("Value to Find", 
               Type.Missing, 
               Type.Missing, 
               Type.Missing, 
               Type.Missing, 
               Excel.XlSearchDirection.xlNext, 
               Type.Missing, 
               Type.Missing, Type.Missing); 

range.Text; //give you the value found 

Dưới đây là một ví dụ khác lấy cảm hứng từ này site:

range = sheet.Cells.Find("Value to find", Type.Missing, Type.Missing,Excel.XlLookAt.xlWhole,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,false, false, Type.Missing); 

Nó giúp hiểu các tham số.

P.S. Tôi là một trong những người kỳ lạ thích học tự động hóa COM. Tất cả mã này được lấy từ một công cụ tôi đã viết cho công việc yêu cầu tôi xử lý hơn 1000 bảng tính từ phòng thí nghiệm vào mỗi thứ Hai.

+0

tôi muốn đọc tệp excel từ Listview để tìm kiếm id email từ tệp excel .... tôi đang cố gắng thực hiện điều này ... nhưng tôi không biết loại mã hóa của excel i có nghĩa là dataformates ... làm thế nào tôi có thể đọc một tập tin excel để tìm kiếm id email ... i dont muốn sử dụng kết nối dữ liệu – ankush

+0

+1 xuất sắc trong câu trả lời sâu sắc. chỉ mất tất cả tên/ngày của 400 + xls tệp ra khỏi một hdd được khôi phục và điều này giúp tôi quay lại đúng hướng trong một giờ – Joe

+1

tại sao dòng khai báo "sử dụng ExcelTools = Ms.Office;" nói "Không thể tìm thấy loại tên hoặc không gian tên 'Ms'"? – Rishi

5

Trước hết, điều quan trọng là phải biết những gì bạn có nghĩa là bằng cách "mở một file Excel để đọc và sao chép nó vào clipboard ..."

này rất quan trọng bởi vì có rất nhiều cách bạn có thể làm điều đó tùy thuộc chỉ về những gì bạn định làm. Hãy để tôi giải thích:

  1. Nếu bạn muốn đọc một tập hợp các dữ liệu và sao chép rằng trong clipboard và bạn biết định dạng dữ liệu (ví dụ như tên cột), tôi đề nghị bạn sử dụng một OleDbConnection để mở tập tin , theo cách này bạn có thể xử lý nội dung tệp xls dưới dạng Bảng cơ sở dữ liệu, vì vậy bạn có thể đọc dữ liệu bằng lệnh SQL và xử lý dữ liệu theo ý muốn.

  2. Nếu bạn muốn thực hiện các thao tác trên dữ liệu với mô hình đối tượng Excel, hãy mở nó theo cách bạn bắt đầu. Một số thời gian có thể xử lý tệp xls dưới dạng tệp csv, có các công cụ như File Helpers cho phép bạn xử lý và mở tệp xls một cách đơn giản bằng cách ánh xạ cấu trúc trên một đối tượng tùy ý.

Một điểm quan trọng khác là phiên bản Excel của tệp.

tôi có, tiếc là tôi nói, một trải nghiệm mạnh mẽ làm việc với tự động hóa văn phòng ở tất cả các cách khác nhau, ngay cả khi bị chặn trong các khái niệm như ứng dụng tự động hóa, quản lý dữ liệu và Plugins, và nói chung tôi chỉ đề nghị như là phương sách cuối cùng, để sử dụng Excel tự động hóa hoặc Tự động hóa văn phòng để đọc dữ liệu; chỉ khi không có cách nào tốt hơn để hoàn thành nhiệm vụ đó.

Làm việc với tự động hóa có thể nặng về hiệu suất, về chi phí tài nguyên, có thể liên quan đến các vấn đề khác liên quan đến bảo mật và hơn thế nữa. Vì vậy, đề nghị của tôi là suy nghĩ và phân tích tình hình trong nhu cầu của bạn và sau đó đi theo cách tốt hơn.

20

Bạn có thể sử dụng lắp ráp Microsoft.Office.Interop.Excel để xử lý các tệp excel.

  1. Nhấp chuột phải vào dự án của bạn và truy cập Add reference. Thêm Microsoft.Office.Interop.Excel lắp ráp.
  2. Bao gồm using Microsoft.Office.Interop.Excel; để tận dụng lắp ráp.

Đây là đoạn mã mẫu:

using Microsoft.Office.Interop.Excel; 

    //create the Application object we can use in the member functions. 
    Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application(); 
    _excelApp.Visible = true; 

    string fileName = "C:\\sampleExcelFile.xlsx"; 

    //open the workbook 
    Workbook workbook = _excelApp.Workbooks.Open(fileName, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing); 

    //select the first sheet   
    Worksheet worksheet = (Worksheet)workbook.Worksheets[1]; 

    //find the used range in worksheet 
    Range excelRange = worksheet.UsedRange; 

    //get an object array of all of the cells in the worksheet (their values) 
    object[,] valueArray = (object[,])excelRange.get_Value(
       XlRangeValueDataType.xlRangeValueDefault); 

    //access the cells 
    for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row) 
    { 
     for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col) 
     { 
      //access each cell 
      Debug.Print(valueArray[row, col].ToString()); 
     } 
    } 

    //clean up stuffs 
    workbook.Close(false, Type.Missing, Type.Missing); 
    Marshal.ReleaseComObject(workbook); 

    _excelApp.Quit(); 
    Marshal.FinalReleaseComObject(_excelApp); 
+0

Tôi thấy rằng sau các đối tượng COM cần phải được khai báo và sau đó 'ReleaseComObject()' ed trong khi 'dọn dẹp các vật liệu' hoặc người nào khác tôi có một excel zombie exe chạy sau khi hoàn thành mã: Đối tượng' Workbooks' được tạo trên '_excelApp.Workbooks' , đối tượng 'Worksheets' được tạo trên các đối tượng' workbook.Worksheets', 'Range' được tạo trên' worksheet.UsedRange.Rows' và 'worksheet.UsedRange.Columns' và đối tượng' excelRange'. Ngoài ra tôi nghĩ rằng thay thế hai 'bảng tính.UsedRange' sử dụng với biến' excelRange' trong trường hợp nhiều đối tượng COM được tạo ra từ không sử dụng biến hiện có. – Quantic

1

Sử dụng OLEDB kết nối để giao tiếp với các tập tin excel. nó cho kết quả tốt hơn

using System.Data.OleDb; 



       string physicalPath = "Your Excel file physical path"; 
       OleDbCommand cmd = new OleDbCommand(); 
       OleDbDataAdapter da = new OleDbDataAdapter(); 
       DataSet ds = new DataSet(); 
       String strNewPath = physicalPath; 
       String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; 
       String query = "SELECT * FROM [Sheet1$]"; // You can use any different queries to get the data from the excel sheet 
       OleDbConnection conn = new OleDbConnection(connString); 
       if (conn.State == ConnectionState.Closed) conn.Open(); 
       try 
       { 
        cmd = new OleDbCommand(query, conn); 
        da = new OleDbDataAdapter(cmd); 
        da.Fill(ds); 

       } 
       catch 
       { 
        // Exception Msg 

       } 
       finally 
       { 
        da.Dispose(); 
        conn.Close(); 
       } 

Dữ liệu đầu ra sẽ được lưu trữ trong tập dữ liệu, sử dụng đối tượng tập dữ liệu bạn có thể dễ dàng truy cập dữ liệu. Hope tháng này hữu ích

+0

Tôi gặp lỗi tại conn.Open(); sân khấu. Kiểm tra với con đường khác nhau của ... – izbrannick

0

File Excel đọc & Writer Without Excel trên hệ thống u'r

  • Tải và thêm dll cho dự án NPOI u'r.
  • Sử dụng mã này để đọc tệp excel.

     using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
         { 
          XSSFWorkbook XSSFWorkbook = new XSSFWorkbook(file); 
         } 
         ISheet objxlWorkSheet = XSSFWorkbook.GetSheetAt(0); 
         int intRowCount = 1; 
         int intColumnCount = 0; 
         for (; ;) 
         { 
          IRow Row = objxlWorkSheet.GetRow(intRowCount); 
          if (Row != null) 
          { 
           ICell Cell = Row.GetCell(0); 
           ICell objCell = objxlWorkSheet.GetRow(intRowCount).GetCell(intColumnCount); }} 
    
-1
public void excelRead(string sheetName) 
     { 
      Excel.Application appExl = new Excel.Application(); 
      Excel.Workbook workbook = null; 
      try 
      { 
       string methodName = ""; 


       Excel.Worksheet NwSheet; 
       Excel.Range ShtRange; 

       //Opening Excel file(myData.xlsx) 
       appExl = new Excel.Application(); 


       workbook = appExl.Workbooks.Open(sheetName, Missing.Value, ReadOnly: false); 
       NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1); 
       ShtRange = NwSheet.UsedRange; //gives the used cells in sheet 


       int rCnt1 = 0; 
       int cCnt1 = 0; 

       for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++) 
       { 
        for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++) 
        { 
         if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y") 
         { 

          methodName = NwSheet.Cells[rCnt1, cCnt1 - 2].Value2; 
          Type metdType = this.GetType(); 
          MethodInfo mthInfo = metdType.GetMethod(methodName); 

          if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_AddNum" || Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_SubNum") 
          { 
           StaticVariable.intParam1 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 3].Value2); 
           StaticVariable.intParam2 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 4].Value2); 
           object[] mParam1 = new object[] { StaticVariable.intParam1, StaticVariable.intParam2 }; 
           object result = mthInfo.Invoke(this, mParam1); 
           StaticVariable.intOutParam1 = Convert.ToInt32(result); 
           NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = Convert.ToString(StaticVariable.intOutParam1) != "" ? Convert.ToString(StaticVariable.intOutParam1) : String.Empty; 
          } 

          else 
          { 
           object[] mParam = new object[] { }; 
           mthInfo.Invoke(this, mParam); 

           NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = StaticVariable.outParam1 != "" ? StaticVariable.outParam1 : String.Empty; 
           NwSheet.Cells[rCnt1, cCnt1 + 6].Value2 = StaticVariable.outParam2 != "" ? StaticVariable.outParam2 : String.Empty; 
          } 
          NwSheet.Cells[rCnt1, cCnt1 + 1].Value2 = StaticVariable.resultOut; 
          NwSheet.Cells[rCnt1, cCnt1 + 2].Value2 = StaticVariable.resultDescription; 
         } 

         else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "N") 
         { 
          MessageBox.Show("Result is No"); 
         } 
         else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "EOF") 
         { 
          MessageBox.Show("End of File"); 
         } 

        } 
       } 

       workbook.Save(); 
       workbook.Close(true, Missing.Value, Missing.Value); 
       appExl.Quit(); 
       System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ShtRange); 
       System.Runtime.InteropServices.Marshal.FinalReleaseComObject(NwSheet); 
       System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook); 
       System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExl); 
      } 
      catch (Exception) 
      { 
       workbook.Close(true, Missing.Value, Missing.Value); 
      } 
      finally 
      { 
       GC.Collect(); 
       GC.WaitForPendingFinalizers(); 
       System.Runtime.InteropServices.Marshal.CleanupUnusedObjectsInCurrentContext(); 
      } 
     } 

//code for reading excel data in datatable 
public void testExcel(string sheetName) 
     { 
      try 
      { 
       MessageBox.Show(sheetName); 

       foreach(Process p in Process.GetProcessesByName("EXCEL")) 
       { 
        p.Kill(); 
       } 
       //string fileName = "E:\\inputSheet"; 
       Excel.Application oXL; 
       Workbook oWB; 
       Worksheet oSheet; 
       Range oRng; 


       // creat a Application object 
       oXL = new Excel.Application(); 




       // get WorkBook object 
       oWB = oXL.Workbooks.Open(sheetName); 


       // get WorkSheet object 
       oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1]; 
       System.Data.DataTable dt = new System.Data.DataTable(); 
       //DataSet ds = new DataSet(); 
       //ds.Tables.Add(dt); 
       DataRow dr; 


       StringBuilder sb = new StringBuilder(); 
       int jValue = oSheet.UsedRange.Cells.Columns.Count; 
       int iValue = oSheet.UsedRange.Cells.Rows.Count; 


       // get data columns 
       for (int j = 1; j <= jValue; j++) 
       { 
        oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j]; 
        string strValue = oRng.Text.ToString(); 
        dt.Columns.Add(strValue, System.Type.GetType("System.String")); 
       } 


       //string colString = sb.ToString().Trim(); 
       //string[] colArray = colString.Split(':'); 


       // get data in cell 
       for (int i = 2; i <= iValue; i++) 
       { 
        dr = dt.NewRow(); 
        for (int j = 1; j <= jValue; j++) 
        { 
         oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j]; 
         string strValue = oRng.Text.ToString(); 
         dr[j - 1] = strValue; 


        } 
        dt.Rows.Add(dr); 
       } 
       if(StaticVariable.dtExcel != null) 
       { 
        StaticVariable.dtExcel.Clear(); 
        StaticVariable.dtExcel = dt.Copy(); 
       } 
       else 
       StaticVariable.dtExcel = dt.Copy(); 

       oWB.Close(true, Missing.Value, Missing.Value); 
       oXL.Quit(); 
       MessageBox.Show(sheetName); 

      } 

      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
      finally 
      { 

      } 
     } 

//code for class initialize 
public static void startTesting(TestContext context) 
     { 

      Playback.Initialize(); 
      ReadExcel myClassObj = new ReadExcel(); 
      string sheetName=""; 
      StreamReader sr = new StreamReader(@"E:\SaveSheetName.txt"); 
      sheetName = sr.ReadLine(); 
      sr.Close(); 
      myClassObj.excelRead(sheetName); 
      myClassObj.testExcel(sheetName); 
     } 

//code for test initalize 
public void runValidatonTest() 
     { 

      DataTable dtFinal = StaticVariable.dtExcel.Copy(); 
      for (int i = 0; i < dtFinal.Rows.Count; i++) 
      { 
       if (TestContext.TestName == dtFinal.Rows[i][2].ToString() && dtFinal.Rows[i][3].ToString() == "Y" && dtFinal.Rows[i][4].ToString() == "TRUE") 
       { 
        MessageBox.Show(TestContext.TestName); 
        MessageBox.Show(dtFinal.Rows[i][2].ToString()); 
        StaticVariable.runValidateResult = "true"; 
        break; 
       } 
      } 
      //StaticVariable.dtExcel = dtFinal.Copy(); 
     } 
4
try 
     { 
      DataTable sheet1 = new DataTable("Excel Sheet"); 
      OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder(); 
      csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0"; 
      csbuilder.DataSource = fileLocation; 
      csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES"); 
      string selectSql = @"SELECT * FROM [Sheet1$]"; 
      using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString)) 
      using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection)) 
      { 
       connection.Open(); 
       adapter.Fill(sheet1); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.Message); 
     } 

này đã làm việc cho tôi. Vui lòng thử và cho tôi biết các truy vấn.

+1

Mã của bạn hoạt động hoàn hảo cho tôi, mà không cần cài đặt bất kỳ thư viện hoặc lịch sử khác, cảm ơn –

-2

Tôi khuyên bạn nên sử dụng Bảng tính Bytescout.

https://bytescout.com/products/developer/spreadsheetsdk/bytescoutspreadsheetsdk.html

Tôi đã thử nó với MonoDevelop trong Unity3D và nó là khá thẳng về phía trước. Kiểm tra mẫu mã này để xem cách thư viện hoạt động:

https://bytescout.com/products/developer/spreadsheetsdk/read-write-excel.html

+0

Cảm ơn bạn đã giới thiệu ByteScout Spreadsheet SDK, vui vì nó hoạt động OK cho bạn trong Monodevelop trong Unity3D! Chúng tôi đã không thử với Unity3D nhưng có lẽ chúng ta nên thử và thêm nó vào danh sách các mẫu mã nguồn –

+0

Bạn đang chào đón @EugeneM! Bạn luôn có thể mở rộng danh sách các giải pháp để có nhiều khả năng lựa chọn hơn. – MetalxBeat

0

Sử dụng Open XML.

Dưới đây là một số mã để xử lý bảng tính với tên tab hoặc trang tính cụ thể và đổ nó vào một cái gì đó như CSV. (Tôi đã chọn một đường ống thay vì dấu phẩy).

Tôi ước rằng việc lấy giá trị từ một ô trở nên dễ dàng hơn, nhưng tôi nghĩ đây là những gì chúng ta đang mắc phải. Bạn có thể thấy rằng tôi tham khảo các tài liệu MSDN nơi tôi nhận được hầu hết các mã này. Đó là những gì Microsoft khuyến cáo.

/// <summary> 
    /// Got code from: https://msdn.microsoft.com/en-us/library/office/gg575571.aspx 
    /// </summary> 
    [Test] 
    public void WriteOutExcelFile() 
    { 
     var fileName = "ExcelFiles\\File_With_Many_Tabs.xlsx"; 
     var sheetName = "Submission Form"; // Existing tab name. 
     using (var document = SpreadsheetDocument.Open(fileName, isEditable: false)) 
     { 
      var workbookPart = document.WorkbookPart; 
      var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName); 
      var worksheetPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id)); 
      var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); 

      foreach (var row in sheetData.Elements<Row>()) 
      { 
       foreach (var cell in row.Elements<Cell>()) 
       { 
        Console.Write("|" + GetCellValue(cell, workbookPart)); 
       } 
       Console.Write("\n"); 
      } 
     } 
    } 

    /// <summary> 
    /// Got code from: https://msdn.microsoft.com/en-us/library/office/hh298534.aspx 
    /// </summary> 
    /// <param name="cell"></param> 
    /// <param name="workbookPart"></param> 
    /// <returns></returns> 
    private string GetCellValue(Cell cell, WorkbookPart workbookPart) 
    { 
     if (cell == null) 
     { 
      return null; 
     } 

     var value = cell.CellFormula != null 
      ? cell.CellValue.InnerText 
      : cell.InnerText.Trim(); 

     // If the cell represents an integer number, you are done. 
     // For dates, this code returns the serialized value that 
     // represents the date. The code handles strings and 
     // Booleans individually. For shared strings, the code 
     // looks up the corresponding value in the shared string 
     // table. For Booleans, the code converts the value into 
     // the words TRUE or FALSE. 
     if (cell.DataType == null) 
     { 
      return value; 
     } 
     switch (cell.DataType.Value) 
     { 
      case CellValues.SharedString: 

       // For shared strings, look up the value in the 
       // shared strings table. 
       var stringTable = 
        workbookPart.GetPartsOfType<SharedStringTablePart>() 
         .FirstOrDefault(); 

       // If the shared string table is missing, something 
       // is wrong. Return the index that is in 
       // the cell. Otherwise, look up the correct text in 
       // the table. 
       if (stringTable != null) 
       { 
        value = 
         stringTable.SharedStringTable 
          .ElementAt(int.Parse(value)).InnerText; 
       } 
       break; 

      case CellValues.Boolean: 
       switch (value) 
       { 
        case "0": 
         value = "FALSE"; 
         break; 
        default: 
         value = "TRUE"; 
         break; 
       } 
       break; 
     } 
     return value; 
    } 
Các vấn đề liên quan