簡體   English   中英

如何在不打開c#winforms中的excel文件的情況下將excel工作表復制到另一個excel工作簿中?

[英]How to copy excel worksheets Into another excel workbook without opening the excel file in c# winforms?

在C#windows應用程序中,我有很多excel工作簿,我想要的是將工作表從excel工作簿復制到單個工作簿。 這是可能的,但我必須打開excel工作簿才能這樣做。

        Excel.Application app = new Excel.Application();

        app.Visible = true;

        app.WindowState = XlWindowState.xlMinimized;

        app.Workbooks.Add("");
        app.Workbooks.Add(@"Path\WorkBook1.xlsx");
        app.Workbooks.Add(@"Path\WorkBook2.xlsx");

        for (int i = 2; i <= app.Workbooks.Count; i++)
        {
            int count = app.Workbooks[i].Worksheets.Count;

            app.Workbooks[i].Activate();
            for (int j = 1; j <= count; j++)
            {
                Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];

                ws.Select(true);
                ws.Cells.Select();

                Excel.Range sel = (Excel.Range)app.Selection;
                sel.Copy(Type.Missing);

                Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing
                    );

                sheet.Paste(Type.Missing, Type.Missing);

                sheet.Name = app.Workbooks[i].Worksheets[j].Name;
            }


        }

        app.DisplayAlerts = false;
        app.Workbooks[3].Close();
        app.Workbooks[2].Close();
        app.DisplayAlerts = true;

        Cursor = Cursors.Default;

        MessageBox.Show("Successfully Generated Excel...!", "Excel Tool", MessageBoxButtons.OK, MessageBoxIcon.Information);

是否可以在不打開Excel工作表的情況下復制所有數據?

要復制工作表及其所有內容和格式而不選擇和復制工作表本身的內容,您可以使用Worksheet.Copy 你會這樣使用它:

Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
                Type.Missing, Type.Missing, Type.Missing, Type.Missing
                );
ws.Copy(Before: sheet);

但是,如果您的問題實際上意味着您希望將工作簿的內容復制到一個通用工作簿而不打開文件,那么我不相信這是可能的。 您需要打開文件才能訪問數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM