简体   繁体   English

将Excel工作表复制到包括格式在内的新工作表-C#

[英]Copy an Excel sheet to new sheet including formatting - C#

I need to create one method that it's able to copy an excel sheet and then, paste it on a new excel sheet in the same workbook, but it's necessary to copy the formatting as well. 我需要创建一种方法,该方法能够复制excel工作表,然后将其粘贴到同一工作簿中的新excel工作表中,但是还必须复制格式。

I found several codes, but all of them not copy the formatting, only the text. 我找到了几个代码,但是所有代码都没有复制格式,仅复制了文本。 below the code that I wrote: 在我编写的代码下面:

        // 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);

If anybody has any suggestion, please let me know. 如果有人有任何建议,请告诉我。

Thanks, 谢谢,

This will make an exact copy of a sheet to a new sheet renamed as the original : 这会将工作表的精确副本复制到重命名为原始工作表的新工作表中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM