小编Ach*_*les的帖子

如何在不打开c#winforms中的excel文件的情况下将excel工作表复制到另一个excel工作簿中?

在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 …
Run Code Online (Sandbox Code Playgroud)

c# com excel ms-office winforms

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

com ×1

excel ×1

ms-office ×1

winforms ×1