winfrom export to microsoft Excel in

1: Add a reference to microsoft excel

 

2: winform form the Add button, named for the export exe

 

 3: Double-click the "Export exe" button, write the code

string fileName = "";

            string saveFileName = "";

            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.DefaultExt = "xls";

            saveDialog.Filter = "Excel Files | * .xls";

            saveDialog.FileName = fileName;

            saveDialog.ShowDialog ();

            saveFileName = saveDialog.FileName; 

            if (saveFileName.IndexOf ( ":") <0) return; // point is canceled

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

            if (xlApp == null)

            {

                MessageBox.Show ( "Unable to create Excel object, your computer may not be installed Excel");

                return;

            }

            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;

            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 

            //写入标题             

            for (int i = 0; i < dataGridView1.ColumnCount; i++)             

            {worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;}

            //写入数值

            for (int r = 0; r < dataGridView1.Rows.Count; r++)

            { for (int i = 0; i < dataGridView1.ColumnCount; i++) 

            { 

                worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;

            } 

                System.Windows.Forms.Application.DoEvents();

            }

            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);

           if (saveFileName != "")

           {     

               try 

               {workbook.Saved = true;

                   workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 

               }                  

               catch (Exception ex)                 

               {//fileSaved = false;                      

                   MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);                  

               }             

           }              

            xlApp.Quit();              

GC.Collect();//强行销毁           } 

 

 4:查看导出结果

Guess you like

Origin www.cnblogs.com/zhongruanzikong/p/12187232.html