daixinet

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
//合并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 on 2012-11-30 15:18  daixinet.com  阅读(354)  评论(0编辑  收藏  举报