从excel中读取客户数据到数组中

本文关键字:数组 数据 读取 excel 客户 | 更新日期: 2023-09-27 17:52:57

我是新的编码,我试图获得信息(Id num,姓名,生日)的每个客户到自己的数组。到目前为止,我能够从excel中读取数据,我只是不知道如何将其存储在数组中,我不确定如何将"valueArray"从对象转换为字符串数组

static void Main(string[] args)
{
    // Reference to Excel Application.
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath("excelpractice1.xlsx"));
    // Get the first worksheet.
    Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
    // Get the range of cells which has data.
    Excel.Range xlRange = xlWorksheet.UsedRange;
    // Get an object array of all of the cells in the worksheet with their values.
    object[,] valueArray = (object[,])xlRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);
    // iterate through each cell and display the contents.
    for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row)
    {
        Console.WriteLine(valueArray[row, row].ToString());
    } 
    // Close the Workbook.
    xlWorkbook.Close(false);
    // Relase COM Object by decrementing the reference count.
    Marshal.ReleaseComObject(xlWorkbook);
    // Close Excel application.
    xlApp.Quit();
    // Release COM object.
    Marshal.FinalReleaseComObject(xlApp);
    Console.ReadLine();
}

从excel中读取客户数据到数组中

像这样:

String[,] arr = new String[xlWorksheet.UsedRange.Rows.Count,xlWorksheet.UsedRange.Columns.Count];
for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row)
{
      for (int col = 1; col <= xlWorksheet.UsedRange.Columns.Count; ++col)
      {
        arr[row,col] = valueArray[row, col].ToString();
      } 
}

您也可以像这样使用Array.Copy

顺便说一句。不确定,但我认为你也应该释放xlRange