Tri*_*dhi 2 c# excel excel-interop
为了合并两个 Excel 表,我使用了下面的代码。
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace MergeWorkBooks
{
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
app.Visible = true;
app.Workbooks.Add("");
app.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");
app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");
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(Type.Missing);
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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码对我合并 excel 工作簿很有用。但是在合并时我没有得到 excel 表名称。在这里,我需要当 excel 同时合并时,工作表名称也应该转到合并的 excel 工作表中。
以下对我来说很好用,包括复制名称和名称冲突的地方,它甚至处理了 Sheet1(2) 等。
Excel.Application app = new Excel.Application();
app.Visible = true;
app.Workbooks.Add("");
app.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");
app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
for (int j = 1; j <= app.Workbooks[i].Worksheets.Count;j++ )
{
Excel.Worksheet ws = app.Workbooks[i].Worksheets[j];
ws.Copy(app.Workbooks[1].Worksheets[1]);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16160 次 |
| 最近记录: |