1 private void BtnExportExcelClick(object sender, EventArgs e)
 2         {
 3             var fromFileName = "D:/Excel/Book2.xls";
 4             var toFileName = "D:/Excel/Book3.xls";
 5 
 6             var saveFileDialog = new SaveFileDialog();
 7 
 8             saveFileDialog.Title = "保存";
 9             saveFileDialog.Filter = "Excel文档(*.xls)|*.xlsx";
10             saveFileDialog.RestoreDirectory = true;
11             if (saveFileDialog.ShowDialog() == DialogResult.OK)
12             {
13                 toFileName = saveFileDialog.FileName;
14             }
15             
16 
17            
18             Microsoft.Office.Interop.Excel._Application appExcel = new ApplicationClass();
19 
20             Microsoft.Office.Interop.Excel.Workbook workbook = appExcel.Workbooks.Open(fromFileName,
21                      Type.Missing, Type.Missing, Type.Missing, Type.Missing,
22                      Type.Missing, Type.Missing, Type.Missing, Type.Missing,
23                      Type.Missing, Type.Missing, Type.Missing, Type.Missing,
24                      Type.Missing, Type.Missing);//打开Excel
25 
26             //Workbook workbook = appExcel.Workbooks.Add(true);
27 
28             Worksheet xlsheet = (Worksheet)workbook.Worksheets[1];
29 
30             Range range = xlsheet.get_Range(appExcel.Cells[1, 1], appExcel.Cells[1, 1]);
31 
32             range.MergeCells = true;
33             appExcel.ActiveCell.FormulaR1C1 = "这是Excel的标题";
34             appExcel.ActiveCell.Font.Size = 20;
35             appExcel.ActiveCell.Font.Bold = true;
36             appExcel.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
37 
38             //开始写入每列的标题 
39             xlsheet.Cells[1,1] = "这是列的标题";
40 
41             //开始写入每列的数据 
42             for (int i = 1; i < 30; i++)
43             {
44                 xlsheet.Cells[i + 2, 1] = "这是列A"+i;
45                 xlsheet.Cells[i + 2, 2] = "这是列B" + i;
46                 xlsheet.Cells[i + 2, 3] = "这是列C" + i;
47                 xlsheet.Cells[i + 2, 4] = "这是列D" + i;
48                 xlsheet.Cells[i + 2, 5] = "这是列E" + i;
49                 xlsheet.Cells[i + 2, 6] = "这是列F" + i;
50                 xlsheet.Cells[i + 2, 7] = "这是列G" + i;
51                 xlsheet.Cells.ColumnWidth = 30;
52             }
53             
54 
55             workbook.Saved = true;
56             workbook.SaveCopyAs(toFileName);
57 
58             workbook.Close();
59 
60             appExcel.Quit();
61             GC.Collect();
62 
63             MessageBox.Show("[XXXXXXX]报表导出成功!","乐家购物",MessageBoxButtons.OK,MessageBoxIcon.Information);
64 
65         }

 

posted on 2013-12-30 11:37  西城诸葛  阅读(747)  评论(0编辑  收藏  举报