简体   繁体   中英

How to Export datagridview to excel file

I have a datagirdview data with 5 columns include 1 columns id and 4 columns text. Besida that, I was exported to excel file but it just show 5 records while my datagridview have more records. How can I export to excel file with condition datagridvew just have 1 record, 3 records... I have a code, could anyone help me? :

 private void Btnexport_Click(object sender, EventArgs e)
    {
        saveFileDialog1.InitialDirectory = "C:";
        saveFileDialog1.Title = "Save as Excel File";
        saveFileDialog1.FileName = "";
        saveFileDialog1.Filter = "Excel File(2003)|*.xls|Excel File(2007)|*.xlsx";
        if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(Type.Missing);

            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                excel.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            for (int i =0; i < dataGridView1.Columns.Count;i++ )
            {
                for(int j=0; j < dataGridView1.Columns.Count; j++)
                {
                    excel.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

                }
            }
            excel.ActiveWorkbook.SaveCopyAs(saveFileDialog1.FileName.ToString());
            excel.ActiveWorkbook.Saved = true;
            excel.Quit();
        }
    }

I think you can simply change the 2nd for loop's Columns to Rows , and the exported data will be right. Besides, do you guarantee all the cells are not empty? If empty, ToString() will throw exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM