C# 使用Excel模板复制单元格

string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = “test”;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0)
{
      //被点了取消
      return;
}


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

string filePath = "c:\test.xls";
Workbooks workbooks = xlApp.Workbooks;
Workbook workbook = workbooks.Add(filePath);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
int startRow = 4;
int totalColumns = 8;
int totalRows = 10;
Range templateRange = worksheet.get_Range(worksheet.Cells[startRow, 1], worksheet.Cells[startRow, totalColumns]);
Range targetRange = worksheet.get_Range(worksheet.Cells[startRow, 1], worksheet.Cells[startRow + totalRows, totalColumns]);
templateRange.Copy(targetRange);

System.Windows.Forms.Application.DoEvents();
   //列宽自适应
 worksheet.Columns.EntireColumn.AutoFit();
  //列高自适应
 worksheet.Rows.EntireRow.AutoFit();  
try
  {
   //设置禁止弹出保存和覆盖的询问提示框    
     xlApp.DisplayAlerts = false;
     xlApp.AlertBeforeOverwriting = false;
    //保存工作簿    
    workbook.Save();
    //保存excel文件    
    xlApp.Save(saveFileName);
     xlApp.SaveWorkspace(saveFileName);
     xlApp.Quit();
     xlApp = null;
  }catch (Exception ex)
    {
        MessageBox.Show("EXCEL文件已填充完毕,但在保存时发生错误");
   }
 
templateRange是源区域,targetRange是目标区域,调用源区域的Copy方法将内容整个复制到目标区域。

你可能感兴趣的:(exception,工作,String,Excel,C#,null)