如何将特定 excel 范围导入到 datagridview

How to import specific excel range to datagridview

我想使用 GemBox 将 excel 文件导入到 datagridview。我是 GemBox 的新手,我似乎不知道怎么做。我只想从单元格“A9”导入到单元格“H32”。

var workbook = ExcelFile.Load(openFileDialog.FileName);

                DataGridViewConverter.ExportToDataGridView(workbook.Worksheets.ActiveWorksheet, this.dgvMain, new ExportToDataGridViewOptions() { ColumnHeaders = true });

谢谢!

以下是导入特定单元格的方法:

var workbook = ExcelFile.Load(openFileDialog.FileName);
var worksheet = workbook.Worksheets.ActiveWorksheet;

var options = new ExportToDataGridViewOptions();
options.ColumnHeaders = true;
options.StartRow = 8;        // Start from row 9, index 8.
options.NumberOfRows = 24;   // End with row 32.
options.StartColumn = 0;     // start with column A, index 0.
options.NumberOfColumns = 8; // End with column H.

DataGridViewConverter.ExportToDataGridView(worksheet, this.dgvMain, options);

还有另一种方法可以指定相同的内容,使用 CellRange 对象的属性:

var workbook = ExcelFile.Load(openFileDialog.FileName);
var worksheet = workbook.Worksheets.ActiveWorksheet;
var range = worksheet.Cells.GetSubrange("A9:H32");

var options = new ExportToDataGridViewOptions();
options.ColumnHeaders = true;
options.StartRow = range.FirstRowIndex;
options.NumberOfRows = range.Height;
options.StartColumn = range.FirstColumnIndex;
options.NumberOfColumns = range.Width;

DataGridViewConverter.ExportToDataGridView(worksheet, this.dgvMain, options);