net操作excel(利用com).docVIP

  • 8
  • 0
  • 约3.66万字
  • 约 30页
  • 2017-02-05 发布于北京
  • 举报
net操作excel(利用com)

写入Excel内容,参数:excelTable是要导入excel的一个table表 view plaincopy to clipboardprint? public?static?bool?SaveDataTableToExcel(System.Data.DataTable?excelTable,?string?filePath)?? ????????{?? ????????????Microsoft.Office.Interop.Excel.Application?app?=?? ????????????????new?Microsoft.Office.Interop.Excel.ApplicationClass();?? ????????????try?? ????????????{?? ????????????????app.Visible?=?false;?? ????????????????Workbook?wBook?=?app.Workbooks.Add(true);?? ????????????????Worksheet?wSheet?=?wBook.Worksheets[1]?as?Worksheet;?? ????????????????if?(excelTable.Rows.Count??0)?? ????????????????{?? ????????????????????int?row?=?0;?? ????????????????????row?=?excelTable.Rows.Count;?? ????????????????????int?col?=?excelTable.Columns.Count;?? ????????????????????for?(int?i?=?0;?i??row;?i++)?? ????????????????????{?? ????????????????????????for?(int?j?=?0;?j??col;?j++)?? ????????????????????????{?? ????????????????????????????string?str?=?excelTable.Rows[i][j].ToString();?? ????????????????????????????wSheet.Cells[i?+?2,?j?+?1]?=?str;?? ????????????????????????}?? ????????????????????}?? ????????????????}?? ?? ????????????????int?size?=?excelTable.Columns.Count;?? ????????????????for?(int?i?=?0;?i??size;?i++)?? ????????????????{?? ????????????????????wSheet.Cells[1,?1?+?i]?=?excelTable.Columns[i].ColumnName;?? ????????????????}?? ????????????????//设置禁止弹出保存和覆盖的询问提示框? ?? ????????????????app.DisplayAlerts?=?false;?? ????????????????app.AlertBeforeOverwriting?=?false;?? ????????????????//保存工作簿? ?? ????????????????wBook.Save();?? ????????????????//保存excel文件? ?? ????????????????app.Save(filePath);?? ????????????????app.SaveWorkspace(filePath);?? ????????????????app.Quit();?? ????????????????app?=?null;?? ????????????????return?true;?? ????????????}?? ????????????catch?(Exception?err)?? ????????????{?? ????????????????MessageBox.Show(导出Excel出错!错误原因:?+?err.Message,?提示信息,?? ????????????????????MessageBoxButtons.OK,?MessageBoxIcon.Information);?? ????????????????return?false;?? ????????????}?? ?

文档评论(0)

1亿VIP精品文档

相关文档