合并Excel文件

//合并Excel文件
        private void MargeExcelFile(string destFile, string dirPath)
        {
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            FileInfo[] files = dir.GetFiles("*.xlsx");

            Microsoft.Office.Interop.Excel.Application app = app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook m_Workbook = null;
            try
            {
                Microsoft.Office.Interop.Excel._Workbook result = app.Workbooks.Add();
                foreach (var item in files)
                {
                    m_Workbook = app.Workbooks.Open(Path.GetFullPath(item.FullName));
                    foreach (Microsoft.Office.Interop.Excel._Worksheet each in m_Workbook.Sheets)
                    {
                        each.Copy(result.Worksheets[1]);
                    }
                }
                if (File.Exists(destFile) == true)
                {
                    File.Delete(destFile);
                }
                result.SaveAs(destFile);
            }
            catch
            {
            }
            finally
            {
                if (m_Workbook != null)
                {
                    m_Workbook.Close();
                }
                app.Quit();
            }
        }

 

posted @ 2013-11-19 14:58  云中雀  阅读(262)  评论(0编辑  收藏  举报