我在Excel中有一个表格,我想在excel中将选定区域导入2D数组。它必须与C#中的2D数组相同。我有一张照片,请看一下。我想将该区域导入int array[81,81]
:
答案 0 :(得分:0)
您可以使用GemBox.Spreadsheet库(您可以使用其免费版本来实现此目的)。
以下是您可以使用的示例:
ExcelFile workbook = ExcelFile.Load("guncellenmis.xlsx");
ExcelWorksheet worksheet = workbook.Worksheets.ActiveWorksheet;
int count = 81;
int[,] data = new int[count, count];
// Get range from "C2" to "CE82".
CellRange range = worksheet.Cells.GetSubrangeRelative(1, 2, count, count);
// Or you can retrieve the required range differently, like:
//CellRange range = worksheet.Cells.GetSubrangeRelative("C2:CE82");
//CellRange range = worksheet.Cells.GetSubrangeRelative("C2", "CE82");
// etc.
for (int row = 0; row < range.Height; ++row)
for (int column = 0; column < range.Width; ++column)
data[row, column] = range[row, column].IntValue;
编辑: 您是否有理由将excel文件导出为2D数组而不是DataTable 您可以将所需数据作为DataTable进行检索,如下所示:
ExcelFile workbook = ExcelFile.Load("guncellenmis.xlsx");
ExcelWorksheet worksheet = workbook.Worksheets.ActiveWorksheet;
DataTable table = worksheet.CreateDataTable(
new CreateDataTableOptions("C2", 81, 81));