将特定范围从CSV文件导入datagridview

时间:2017-07-06 07:05:46

标签: c# csv datagridview

我从这个link复制了这些代码并尝试了它。

然而,它对我不起作用。我的代码有什么问题或有其他方法吗?或者应该对代码进行任何改进。代码如下。

当我选择了范围并按下确定时,没有任何反应。

Nothing will appear in my datagridview

        private Microsoft.Office.Interop.Excel._Application App;
    private Microsoft.Office.Interop.Excel.Range rng = null;

    private System.Data.DataTable ConvertRangeToDataTable()
    {
        try
        {
            System.Data.DataTable dt = new System.Data.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 button1_Click(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 Microsoft.Office.Interop.Excel.Application();
            App.Visible = true;
            App.Workbooks.Open(OFD.FileName);
        }
        else { return; }

        try
        {
            rng = (Microsoft.Office.Interop.Excel.Range)App.InputBox("Please select a range", "Range Selection");
        }
        catch { App.Quit(); }; //user pressed cancel on input box

        if (rng != null)
        {
            System.Data.DataTable dt = ConvertRangeToDataTable();
            if (dt != null)
            {
                dataGridView1.DataSource = dt;
            }
            Dispose();
        }
    }
    private void Dispose()
    {
        try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(rng); }
        catch { }
        finally { rng = null; }
        try { App.Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(App); }
        catch { }
        finally { App = null; }
    }

0 个答案:

没有答案