winform导出到excel 不指定

Else , 2010/08/20 18:38 , 代码片段,演示也有 , Comments(0) , Reads(1939) , Via Original
public void toExcel(System.Windows.Forms.DataGridView dataGridView1)
        {
            //导出到execl    
            try
            {
                //没有数据的话就不往下执行    
                if (dataGridView1.Rows.Count == 0)
                    return;
                //实例化一个Excel.Application对象
                //  Interop .Excel .Application

                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

                //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写    
                excel.Visible = false;

                //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错    
                excel.Application.Workbooks.Add(true);
                //生成Excel中列头名称    
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                }
                //把DataGridView当前页的数据保存在Excel中    
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        if (dataGridView1[j, i].ValueType == typeof(string))
                        {
                            excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString();
                        }
                        else
                        {
                            excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
                        }
                    }
                }

                //设置禁止弹出保存和覆盖的询问提示框    
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = false;

                //保存工作簿    
                excel.Application.Workbooks.Add(true).Save();
                //保存excel文件    
                excel.Save("D:" + "\\po_trans_temp.xls");


                //确保Excel进程关闭    
                excel.Quit();
                excel = null;

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "错误提示");
            }
        }

  


private void btn_toexcel3_Click(object sender, EventArgs e)
        {
            toExcel(dataGridView3);
        }
Add a comment

Nickname

Site URI

Email

Enable HTML Enable UBB Enable Emots Hidden Remember [Login] [Register]