我想将特定范围的xls文件导入到datagridview中。问题是:范围每次都在变化,因此我需要用户能够选择它。是否有一种优雅的方式来做到这一点?
答案 0 :(得分:3)
查看此代码是否适合您。它会提示用户打开一个excel文件,然后提示他们输入他们想要在DataGridView中看到的范围。在选择范围后,它将该范围转换为DataTable并将DataTable设置为源。
我不确定您想要使用它或您想要添加的任何其他功能,但这应该为您提供一个构建块。
private Excel.Application App;
private Excel.Range rng = null;
private void button1_Click_1(object sender, EventArgs e) {
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "Excel Worksheets|*.xls;*.xlsx;*.xlsm;*.csv";
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
App = new Excel.Application();
App.Visible = true;
App.Workbooks.Open(OFD.FileName);
}
else { return; }
try { rng = (Excel.Range)App.InputBox("Please select a range", "Range Selection", Type: 8); }
catch { } // user pressed cancel on input box
if (rng != null) {
DataTable dt = ConvertRangeToDataTable();
if (dt != null) { dataGridView1.DataSource = dt; }
}
_Dispose();
}
private DataTable ConvertRangeToDataTable() {
try {
DataTable dt = new DataTable();
int ColCount = rng.Columns.Count;
int RowCount = rng.Rows.Count;
for (int i = 0; i < ColCount; i++) {
DataColumn dc = new DataColumn();
dt.Columns.Add(dc);
}
for (int i = 1; i <= RowCount; i++) {
DataRow dr = dt.NewRow();
for (int j = 1; j <= ColCount; j++) { dr[j - 1] = rng.Cells[i, j].Value2; }
dt.Rows.Add(dr);
}
return dt;
}
catch { return null; }
}
private void _Dispose() {
try { Marshal.ReleaseComObject(rng); }
catch { }
finally { rng = null; }
try { App.Quit(); Marshal.ReleaseComObject(App); }
catch { }
finally { App = null; }
}