如何复制EXCEL导入另一个Excel工作簿,工作表,而无需打开在C#中的WinForms excel文件? [英] How to copy excel worksheets Into another excel workbook without opening the excel file in c# winforms?
问题描述
在C#Windows应用程序,
我有很多的Excel工作簿,我想是到工作表从Excel工作簿复制到一个工作簿。
这是可能的,但我为了做到这一点,打开Excel工作簿。
In C# windows application, I have many excel workbooks, what i want is to copy the worksheets from the excel workbook to a single workbook. This is possible, but i have to open the excel workbooks in order to do so.
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工作表,复制所有他们的风格的数据?
Is is possible without opening the excel sheets, copy all the data with their styles ?
推荐答案
要复制工作表及其所有内容和格式而不选择和复制工作表本身可以利用的内容 Worksheet.Copy 。你会使用它像这样:
To copy a worksheet and all its contents and formatting without selecting and copying the contents of the worksheet itself you can make use of Worksheet.Copy. You'd use it like so:
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);
不过,如果你实际上你的问题的意思是,你要复制的内容工作簿到一个共同的工作簿无需打开文件,然后我不相信这是可能的。你需要打开访问数据的文件。
If, however, what you actually mean by your question is that you want to copy the contents of the workbooks into one common workbook without ever opening the file, then I don't believe that's possible. You need to open the file to access the data.
这篇关于如何复制EXCEL导入另一个Excel工作簿,工作表,而无需打开在C#中的WinForms excel文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!