将Excel工作表复制到新工作表,包括格式化 - C#

时间:2015-01-22 12:31:41

标签: c# excel copy-paste worksheet

我需要创建一个方法,它能够复制Excel工作表,然后将其粘贴到同一工作簿中的新Excel工作表中,但也需要复制格式。

我找到了几个代码,但所有代码都没有复制格式,只复制文本。 在我写的代码下面:

        // Opening Excel File
        Microsoft.Office.Interop.Excel.Application excel = null;
        excel = new Microsoft.Office.Interop.Excel.Application();

        Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(file, 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);
        Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Worksheets;
        Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
        Microsoft.Office.Interop.Excel.Worksheet sheet2 = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(2);


        // Copy the source sheet
        Object defaultArg = Type.Missing;

        sheet = (Worksheet)workbook.Sheets[1];
        sheet.UsedRange.Copy(defaultArg);

        // Paste on destination sheet
        sheet2.UsedRange._PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

        workbook.Save();
        common.closeExcel(excel, workbook);

如果有人有任何建议,请告诉我。

谢谢,

1 个答案:

答案 0 :(得分:-2)

这会将工作表的精确副本重命名为新工作表:

Dim x = 2
For numtimes = 1 To x 
Sheet1.Copy _
After:=Sheet1
Next