有多個結構相同 (含複雜表頭) 的 Excel 檔案,需合併為單一檔案並移除重複表頭資料。透過 COM 元件 (Microsoft.Office.Interop.Excel) 讀取各檔案的 Range 寫入新活頁簿。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication20
{
class Program
{
static void Main(string[] args)
{
// M 為最後一欄標記,3 為表頭列數
MergeExcel.DoMerge(new string[]
{
@"E:\excel\類型A\公司A.xls",
@"E:\excel\類型A\公司B.xls"
}, @"E:\excel\類型A\合併測試.xls", "M", 3);
MergeExcel.DoMerge(new string[]
{
@"E:\excel\類型B\統計表A.xls",
@"E:\excel\類型B\統計表B.xls"
}, @"E:\excel\類型B\合併測試.xls", "I", 4);
}
}
public class MergeExcel
{
Excel.Application app = new Excel.ApplicationClass();
Excel.Workbook bookDest = null, bookSource = null;
Excel.Worksheet sheetDest = null, sheetSource = null;
string[] _sourceFiles; string _destFile, _columnEnd;
int _headerRowCount, _currentRowCount;
public MergeExcel(string[] sourceFiles, string destFile, string columnEnd, int headerRowCount)
{
bookDest = (Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
sheetDest = bookDest.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;
sheetDest.Name = "Data";
_sourceFiles = sourceFiles; _destFile = destFile; _columnEnd = columnEnd; _headerRowCount = headerRowCount;
}
void OpenBook(string fileName) { /* 開啟來源活頁簿 */ }
void CloseBook() { /* 關閉來源活頁簿 */ }
void CopyHeader() { /* 複製表頭至目標 */ }
void CopyData() { /* 複製資料列 (跳過表頭) */ }
void Save() { bookDest.Saved = true; bookDest.SaveCopyAs(_destFile); }
void Quit() { app.Quit(); }
void DoMerge()
{
bool first = false;
foreach (string f in _sourceFiles)
{
OpenBook(f);
if (!first) { CopyHeader(); first = true; }
CopyData();
CloseBook();
}
Save(); Quit();
}
public static void DoMerge(string[] sourceFiles, string destFile, string columnEnd, int headerRowCount)
{
new MergeExcel(sourceFiles, destFile, columnEnd, headerRowCount).DoMerge();
}
}
}
ApplicationClass、目標活頁簿與工作表。get_Range 定義來源與目標區域,呼叫 Copy 方法。Quit() 釋放 COM 物件。