c#dgv或对象数据写入到excel中

1  Microsoft.Office.Interop.Excel.Application objApp = new Microsoft.Office.Interop.Excel.Application();//创建对象
2             Workbook objwork = objApp.Workbooks.Open("D:\\rpt\\快递单ces.xls",Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);//打开路劲为D:\rpt\快递单ces.xls的excel模板
3                                                                                                                                                                                    // Workbook objwork = objApp.Workbooks.Add(Type.Missing); //创建新的excel
4             Worksheet objSheet = (Worksheet)objwork.Worksheets[sheentName];//打开对应的工作表
5             Worksheet objsheet1 = (Worksheet)objwork.Worksheets["Sheet0"]; //把数据写入sheet0工作表
6             objSheet.Activate();
7             objApp.Visible = true;//设置excel可见
8             objsheet1.Cells[1, 2] = tboNumber.Text;//给sheet1工作表的B1单元格赋值

 

 

 

 1  Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();//实例化一个application对象
 2             excelApp.Visible = true;//设置打开的excel为可见
 3             Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Add(Missing.Value);//创建一个新的excel
 4             Microsoft.Office.Interop.Excel.Worksheet sheent = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];//获取excel第一个工作表
 5            
 6             for (int i = 0; i < dataGridView1.Columns.Count; i++)
 7             {
 8                 sheent.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;//写入表头
 9             }
10             for (int i = 0; i < dataGridView1.Rows.Count ; i++)
11             {
12               
13                 for (int j = 0; j < dataGridView1.Columns.Count; j++)
14                 {
15 
16 
17 
18 
19                     sheent.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();//写入数据
20                         
21                     
22 
23                 }
24             }
25             Range range = sheent.Columns;//获取所有单元格
26             range.AutoFit();//设置单元格自适应高度和宽度

 

c#dgv或对象数据写入到excel中

上一篇:原版win10在微软官网下载方法


下一篇:php -- 数组