导航

datagridView数据导出到Excel

Posted on 2009-05-18 20:26  kingwangzhen  阅读(423)  评论(0编辑  收藏  举报

 try
            {
                 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
           excel.Application.Workbooks.Add(true);

           
                if (ds.Tables.Contains("viewPigSlice") && ds.Tables["viewPigSlice"].Rows.Count > 0)
                {
                    //生成字段
                    for(int i=0;i<dgvViewPigSliceInfo.Columns.Count;i++)
                    {
                        excel.Cells[1, i + 1] = dgvViewPigSliceInfo.Columns[i].HeaderCell.Value;
                    }
                    //填充数据
                    for (int i = 0; i < dgvViewPigSliceInfo.Rows.Count; i++)
                    {
                        for(int j=0;j<dgvViewPigSliceInfo.Columns.Count;j++)
                        {
                            if(dgvViewPigSliceInfo.Rows[i].Cells[j].Value==typeof(string))
                            {
                                excel.Cells[i + 2,j + 1] =""+ dgvViewPigSliceInfo.Rows[i].Cells[j].Value.ToString();

                            }else
                            {
                                excel.Cells[i + 2, j + 1] = dgvViewPigSliceInfo.Rows[i].Cells[j].Value.ToString();
 
                            }
                        }
                    }
                  

                    excel.Visible = true;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }