合并选中EXCEL中的各个工作表,以第一个选中的EXCEL文件里的工作表进行匹配,遍历后面的每个EXCEL文件,有相同的工作表就合并:
private void button1_Click(object sender, EventArgs e) { string inifolder = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "EXCEL\\UpdateList";//设定默认文件夹 OpenFileDialog dialog = new OpenFileDialog { Title = "请选择EXCEL文件:", Filter = "EXCEL文件(*.xls*)|*.xls*", Multiselect = true, InitialDirectory = inifolder }; string[] files = null; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { files = dialog.FileNames; } if (files != null) { if (files.Length == 1) { MessageBox.Show("There is only one file seleced, no need to merge!"); return; } Excel.Application merapp = new Excel.Application(); merapp.Visible = true;//设定合并过程是否可视化 Excel.Workbook merwbk = merapp.Workbooks.Open(files[0]); merwbk.SaveAs(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "EXCEL\\UpdateListByMerge\\Subaccount Update List(M)" + DateTime.Now.ToString("_yyyyMMdd_HHmmss") + ".xlsm");//另存第一个EXCEL文件 for (int i = 1; i < files.Length; i++)//遍历后面的EXCEL文件 { Excel.Workbook merdwbk = merapp.Workbooks.Open(files[i]); foreach(Excel.Worksheet sht in merwbk.Worksheets) { Excel.Worksheet mersht = sht; string curshtname = mersht.Name; if (!HasSheet(curshtname, merdwbk)) { continue; } int docidcol = 1; int startrow = 2; switch (mersht.Name) { case "Add": docidcol = 10; startrow = 3; break; case "Close": case "Reopen": case "Merge": case "Liquidate": docidcol = 4; startrow = 3; break; } int endrow = ((Excel.Range)merdwbk.Worksheets[curshtname].Cells[999999, docidcol]).get_End(Excel.XlDirection.xlUp).Row; if (endrow < startrow) continue; int currow = ((Excel.Range)mersht.Cells[999999, docidcol]).get_End(Excel.XlDirection.xlUp).Row; if (curshtname.ToUpper() == "TODOLIST") merdwbk.Worksheets[curshtname].Range["a" + startrow.ToString() + ":f" +endrow.ToString()].Copy(mersht.Range["a" + (currow + 1).ToString()]); else merdwbk.Worksheets[curshtname].Rows[startrow.ToString() + ":" + endrow.ToString()].Copy(mersht.Range["a" + (currow + 1).ToString()]); } merdwbk.Close(false); } merwbk.Save(); merapp.Visible = true; } }
根据工作表名判断EXCEL文件是否含有该工作表:
public bool HasSheet(string shtname, Excel.Workbook wbk) { foreach (Excel.Worksheet w in wbk.Worksheets) { if (w.Name.ToUpper().Trim() == shtname.ToUpper()) { return true; } } return false; }
在合并EXCEL文件时,往往需要计算工作表里需要copy的起始行号和结束行号,要结合实际可能发生的情况统计比较好,例子中使用的是get_End()方法,而不是使用UsedRange或者CurrentRegion确定区域,因为有可能只改变格式也会影响UsedRange,有空行也会影响CurrentRegion,还不如选中一个标准列,统计该标准列中最后一个非空单元格的行号,代表该工作表的结束行号,起始行号一般就是标题除外的第2行或第3行了,当结束行号<起始行号时,就意味着该工作表没有需要合并的。
原文地址:https://www.cnblogs.com/JTCLASSROOM/p/11102265.html
时间: 2024-11-08 19:57:11