将dataGridView中的数据导出到Excel中


//需要引用Microsoft.Office.Excel的数据集

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);
            //输出列名
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
            }
            //对每一列赋值
            for (int i = 0; i < dataGridView1.RowCount-1; i++)
            {
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                {
                    if (dataGridView1[j, i].ValueType == typeof(string))
                    {
                        //excel的列是从1开始
                        excel.Cells[i + 2, j +1] = "'" + dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                    else
                    {
                         excel.Cells[i + 2, j +1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                }
            }
            //设置禁止弹出保存和覆盖的询问提示框  
            excel.Visible = false;
            excel.DisplayAlerts = false;
            excel.AlertBeforeOverwriting = false;


            //保存到临时工作簿
            //excel.Application.Workbooks.Add(true).Save();
            //保存文件
            try
            {
                excel.Save("E:");
                excel.Quit();
                MessageBox.Show("文件导出成功", "完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

猜你喜欢

转载自blog.csdn.net/tzc_xyh/article/details/72843519