gpt4 book ai didi

c# - 使用 C# 实现 Excel 自动化

转载 作者:行者123 更新时间:2023-11-30 12:36:51 24 4
gpt4 key购买 nike

我有一个包含近 400 个 excel 文件的文件夹。我需要将所有这些 excel 文件中的工作表复制到一个 excel 文件中。

使用 Interop 和 Reflection 命名空间是我到目前为止所取得的成就。

我使用 folderBrowserDialog 浏览到文件夹并选择它,这使我能够获取文件夹中文件的文件名并遍历它们,这是我所知道的,任何帮助将不胜感激。

if (result == DialogResult.OK)
{
string path = fbd1.SelectedPath; //get the path
int pathLength = path.Length + 1;
string[] files = Directory.GetFiles(fbd1.SelectedPath);// getting the names of files in that folder

foreach (string i in files)
{
MessageBox.Show("1 " + i);
myExcel.Application excelApp = new myExcel.ApplicationClass();
excelApp.Visible = false;
MessageBox.Show("2 " + i);
myExcel.Workbook excelWorkbook = excelApp.Workbooks.Add(excelApp.Workbooks._Open(i, 0, false, 5, "", "", false, myExcel.XlPlatform.xlWindows, "", true, false, 0, true));
myExcel.Sheets excelSheets = excelWorkbook.Worksheets;
MessageBox.Show("3 " + i);
excelApp.Workbooks.Close();
excelApp.Quit();
}

MessageBox.Show("Done!");
}

如何将复制的工作表附加到目标文件。希望问题很清楚?

谢谢。

最佳答案

使用 Worksheet.Copy(Before, After) 并将之后指定为您想要的任何主文件的最后一个工作表。请注意,您可能需要在 mainApp 中创建一个新的工作表,以便在之后输入一个工作表,这样它就不会抛出异常。

尝试以下操作:

            Excel.Application mainApp = new Excel.ApplicationClass();
mainApp.Visible = false;
Excel.Workbook mainWorkbook = excelApp.Workbooks.Add(null);
Excel.Sheets mainWorkSheets = mainWorkbook.Worksheets;

foreach (string i in files)
{
MessageBox.Show("1 " + i);
Excel.Application exApp = new Excel.ApplicationClass();
exApp.Visible = false;
MessageBox.Show("2 " + i);
Excel.Workbook exWorkbook = exApp.Workbooks.Open(i,
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);
MessageBox.Show("3 " + i);
foreach(Excel.Worksheet sheet in exWorkbook.Worksheets)
{
sheet.Copy(Type.Missing, mainWorkSheets[mainWorkSheets.Count -1]);
}
}

mainApp.Save("NewExcel");

关于c# - 使用 C# 实现 Excel 自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2431840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com