日期:2014-05-18 浏览次数:20776 次
Excel.Application myExcel = new Excel.Application(); myExcel.Visible = true; if (myExcel == null) { MessageBox.Show("Excel无法启动,请确认已正确安装Excel", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Workbooks myWorkbooks = myExcel.Workbooks; Workbook myWorkbook = myWorkbooks.Add(System.Reflection.Missing.Value);//创建Excel工作表 Worksheet myWorksheet = (Worksheet)myWorkbook.Worksheets[1];//创建Excel工作表Sheet1页 Range myRange = myExcel.get_Range(myExcel.Cells[1, 1], myExcel.Cells[1, 9]);//选择页的范 myExcel.Cells[1, 9]表示下面myhead中存入的表头个数 object[] myhead = { "货料编号", "货料名称", "规格型号", "单位", "数量", "单价", "供应商", "入库时间", "小计" };//设置表头 myRange.Value2 = myhead; if (this.dgv_InExport.Rows.Count > 0) { myRange = myWorksheet.get_Range("A2", System.Reflection.Missing.Value); int row = 0; row = this.dgv_InExport.Rows.Count;//设置表的行数 int col = 9;//设置表的列数 object[,] mydata = new object[row, col]; try { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { mydata[i, j] = this.dgv_InExport[j, i].Value.ToString();//读取DataGridView中的值,保存到myData数组中 } } } catch (Exception ex) { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } myRange = myRange.get_Resize(row, col); myRange.Value2 = mydata;//把mydata数组的值存到Excel表导出 myRange.EntireColumn.AutoFit(); } myExcel = null;//清空表单