【问题标题】:How to read data of an Excel file using C#?如何使用 C# 读取 Excel 文件的数据?
【发布时间】:2009-03-18 06:08:10
【问题描述】:

如何使用 C# 读取 Excel 文件?我打开一个 Excel 文件进行阅读并将其复制到剪贴板以搜索电子邮件格式,但我不知道该怎么做。

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

【问题讨论】:

  • 寻求解决方案的新用户可能希望看到这个thread

标签: c# excel


【解决方案1】:

好的,

关于 Excel VSTO 编程的一个更难掌握的概念是,您不能像数组一样引用单元格,Worksheet[0][0] 不会给您单元格 A1,它会在您身上出错。即使您在 Excel 打开时在 A1 中键​​入,您实际上是在将数据输入到 Range A1 中。因此,您将单元格称为命名范围。这是一个例子:

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

您现在可以直接输入:

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)

如果你想做这样的事情:

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

     }

可能有更好的方法,但这对我有用。

您需要使用Value2 而不是Value 的原因是因为Value 属性是参数化的,而C# 还不支持它们。

至于清理代码,我会在明天上班时发布,我没有代码,但它是非常样板的。您只需按照创建对象的相反顺序关闭和释放对象。不能使用 Using() 块,因为 Excel.Application 或 Excel.Workbook 没有实现 IDisposable,如果不清理,您将在内存中留下一个悬挂的 Excel 对象。

注意:

  • 如果您不设置 Visibility 属性 Excel 不会显示,这可能会让您的用户感到不安,但如果您只想提取数据,那可能就足够了
  • 你可以使用 OleDb,它也可以。

我希望这可以帮助您入门,如果您需要进一步说明,请告诉我。我会发一个完整的

这是一个完整的示例:

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

明天我会从 ExcelTools 发布函数,我也没有那个代码。

编辑: 正如所承诺的,这里是您可能需要的 ExcelTools 中的函数。

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

坦率地说,如果您使用 VB.NET,这些东西会容易得多。它在 C# 中,因为我没有编写它。 VB.NET 可以很好地处理选项参数,而 C# 没有,因此 Type.Missing。一旦你连续输入 Type.Missing 两次,你就会尖叫着跑出房间!

至于你的问题,你可以尝试以下:

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

我会在会议回来后发布一个示例...干杯

编辑:这是一个例子

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

这是受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);

有助于理解参数。

附:我是那些喜欢学习 COM 自动化的怪人之一。所有这些代码都来自我为工作而编写的工具,该工具需要我每周一处理来自实验室的 1000 多个电子表格。

【讨论】:

  • 我想从 Listview 读取 excel 文件以从 excel 文件中搜索电子邮件 id....我正在尝试这样做...但我不知道 excel 的编码类型,我的意思是数据格式。 .. 我如何读取 excel 文件来搜索电子邮件 ID...我不想使用数据连接
  • +1 优秀的深度答案。刚刚从恢复的硬盘中丢失了 400 多个 xls 文件的所有名称/日期,这让我在一小时内回到正轨
  • 为什么声明行“使用 ExcelTools = Ms.Office;”说“找不到类型或命名空间名称‘Ms’”?
  • @Rishi Ms.Office 命名空间没什么特别的。它由一个具有静态方法的类组成,该类包装了互操作库的 Open、Save、Add 方法,以提供常见的重载并隐藏 COM 互操作库所需的一些 Type.Missing 和 Missing.Value 参数。如果您希望我发布代码,我可以
  • "VB.NET does option parameters well, C# does not, hence the Type.Missing." 实际上我认为 C# 从 C# 4 开始也可以很好地处理可选参数。有关更多信息,请参见此处:blogs.msdn.com/b/samng/archive/2009/06/16/…
【解决方案2】:

您可以使用Microsoft.Office.Interop.Excel 程序集来处理excel 文件。

  1. 右键单击您的项目并转到Add reference。添加 Microsoft.Office.Interop.Excel 程序集。
  2. 包括using Microsoft.Office.Interop.Excel; 以使用程序集。

这里是示例代码:

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

【讨论】:

  • 我发现需要声明以下COM对象,然后在clean up stuffs期间ReleaseComObject()ed,否则我在代码完成后运行了一个僵尸excel exe:Workbooks object created on @987654328 @,在workbook.Worksheets 上创建的Worksheets 对象,在worksheet.UsedRange.Rowsworksheet.UsedRange.Columns 上创建的Range 对象,以及excelRange 对象。另外我认为用excelRange 变量替换两个worksheet.UsedRange 用法,以防更多的COM 对象是从不使用现有变量创建的。
【解决方案3】:

为什么不创建 OleDbConnection?互联网上有很多可用的资源。这是一个例子

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

【讨论】:

  • 我在使用 OleDbConnection(使用 Oracle 数据适配器)时遇到的一个问题是包含数字和文本的列。我得到了一个数据表,其列格式为数字,其中缺少数据格式为文本的所有单元格。我的解决方案是在使用 OleDBC 获取数据之前,使用 interop 将列的整个使用范围转换为 TEXT 格式。
  • 上次工作存档here。只有 40 行.. 可能只是编辑帖子并添加它们。耸耸肩
【解决方案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);
        }

这对我有用。请尝试一下,如有疑问请告诉我。

【讨论】:

  • 您的代码非常适合我,无需安装任何库或其他历史记录,谢谢
【解决方案5】:

首先,重要的是要了解“打开一个 Excel 文件进行阅读并将其复制到剪贴板...”的意思

这非常重要,因为您可以通过多种方式做到这一点,具体取决于您打算做什么。让我解释一下:

  1. 如果您想读取一组数据并将其复制到剪贴板并且您知道数据格式(例如列名),我建议您使用 OleDbConnection 打开文件,这样你就可以把xls文件内容当成一个Database Table,这样你就可以用SQL指令读取数据,并按照你的意愿对待数据。

  2. 如果您想使用 Excel 对象模型对数据进行操作,请按照您开始的方式打开它。

  3. 有时可以将 xls 文件视为一种 csv 文件,有像 File Helpers 这样的工具允许您通过将结构映射到任意对象。

另一个重要的一点是文件的 Excel 版本。

不幸的是,我在使用 Office 自动化方面拥有丰富的经验,即使受限于应用程序自动化、数据管理和插件等概念,通常我建议仅作为最后的手段,使用 Excel 自动化或办公自动化读取数据;如果没有更好的方法来完成这项任务。

就资源成本而言,使用自动化可能会影响性能,可能涉及与安全性等相关的其他问题,最后但并非最不重要的是,使用 COM 互操作并不是那么“免费”。 所以我的建议是思考和分析你需要的情况,然后采取更好的方法。

【讨论】:

    【解决方案6】:

    使用 OLEDB Connection 与 excel 文件进行通信。效果更好

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

    输出数据将存储在数据集中,使用数据集对象可以轻松访问数据。 希望这可能会有所帮助

    【讨论】:

      【解决方案7】:

      这是 2020 年的答案 - 如果您不需要支持较旧的 .xls 格式(所以在 2003 年之前),您可以使用以下任一格式:

      优点:

      缺点:

      • LightweightExcelReaderExcelToEnumerable 都不支持 .xls 文件。

      免责声明:我是 LightweightExcelReader 和 ExcelToEnumerable 的作者

      【讨论】:

        【解决方案8】:

        使用OlebDB,我们可以轻松读取C#中的excel文件,这是使用Web-Form时的代码,其中FileUpload1是文件上传工具

           string path = Server.MapPath("~/Uploads/");
          if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        //get file path
        filePath = path + Path.GetFileName(FileUpload1.FileName);
        //get file extenstion
        string extension = Path.GetExtension(FileUpload1.FileName);
        //save file on "Uploads" folder of project
        FileUpload1.SaveAs(filePath);
        
        string conString = string.Empty;
        //check file extension
        switch (extension)
        {
            case ".xls": //Excel 97-03.
                conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Excel03ConString;Extended Properties='Excel 8.0;HDR=YES'";
                break;
            case ".xlsx": //Excel 07 and above.
                conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel07ConString;Extended Properties='Excel 8.0;HDR=YES'";
                break;
        }
        
        //create datatable object
        DataTable dt = new DataTable();
        conString = string.Format(conString, filePath);
        
        //Use OldDb to read excel
        using (OleDbConnection connExcel = new OleDbConnection(conString))
        {
            using (OleDbCommand cmdExcel = new OleDbCommand())
            {
                using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                {
                    cmdExcel.Connection = connExcel;
        
                    //Get the name of First Sheet.
                    connExcel.Open();
                    DataTable dtExcelSchema;
                    dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                    connExcel.Close();
        
                    //Read Data from First Sheet.
                    connExcel.Open();
                    cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
                    odaExcel.SelectCommand = cmdExcel;
                    odaExcel.Fill(dt);
                    connExcel.Close();
                }
            }
        }
        
        //bind datatable with GridView
        GridView1.DataSource = dt;
        GridView1.DataBind();
        

        来源:https://qawithexperts.com/article/asp-net/read-excel-file-and-import-data-into-gridview-using-datatabl/209

        控制台应用程序类似代码示例 https://qawithexperts.com/article/c-sharp/read-excel-file-in-c-console-application-example-using-oledb/168

        如果你需要不想使用OleDB,你可以试试https://github.com/ExcelDataReader/ExcelDataReader 它似乎能够处理两种格式(.xls 和 .xslx)

        【讨论】:

          【解决方案9】:

          您的系统上没有 Excel 的 Excel 文件读取器和写入器

          • 下载并添加 dll NPOI你的项目。
          • 使用此代码读取 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); }}
            

          【讨论】:

            【解决方案10】:

            使用Open XML

            下面是一些代码,用于处理具有特定选项卡或工作表名称的电子表格并将其转储到 CSV 之类的文件中。 (我选择了竖线而不是逗号)。

            我希望从单元格中获取值更容易,但我认为这就是我们所坚持的。您可以看到我参考了获得大部分代码的 MSDN 文档。这是微软推荐的。

                /// <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;
                }
            

            【讨论】:

              【解决方案11】:
              【解决方案12】:
              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();
                      }
              

              【讨论】:

                【解决方案13】:

                我建议您使用 Bytescout 电子表格。

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

                我在 Unity3D 中使用 Monodevelop 进行了尝试,它非常简单。检查此示例代码以了解该库的工作原理:

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

                【讨论】:

                • 感谢您推荐 ByteScout Spreadsheet SDK,很高兴它在 Unity3D 中的 Monodevelop 中为您工作正常!我们还没有尝试过 Unity3D,但也许我们现在应该尝试将其添加到源代码示例列表中
                • 不客气@EugeneM!扩大解决方案列表以便有更多选择的可能性总是很好。
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-07-12
                相关资源
                最近更新 更多