1

我想将特定范围的 xls 文件导入 datagridview。问题是:范围每次都在变化,因此我需要用户能够选择它。有没有一种优雅的方式来做到这一点?

4

1 回答 1

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; }
    }
于 2012-10-02T15:32:56.017 回答