如何从特定文件夹中读取多个XLSX文件,并将它们逐个写入单个xlsx文件

时间:2017-04-20 10:57:58

标签: c# .net parsing xlsx

我正在开发一个控制台应用程序,其中给出了文件夹的路径,并且必须从该文件夹中选择所有xlsx文件并将其存储在列表中。然后将它们逐个写入一个新的xlsx文件..我确实尝试了某些代码但是没有工作..

这是我的代码。任何帮助将不胜感激。

static void Main(string[] args)
{
            int rCnt;
            int cCnt;
            int rc = 0;
            int cc = 0;
            string s;

            DirectoryInfo d = new DirectoryInfo(@"D:\T01052\Programs\C#\Programs\Excel into Excel\Excel into Excel\Excel into Excel\Excel file\Input File");

            FileInfo[] Files = d.GetFiles("*.xlsx");

            List<string> lstr = new List<string>();

            int filecount = 0;

            foreach (FileInfo file in Files)
            {
                Excel.Application xlApp = new Excel.Application();
                Excel.Workbook wb = null;
                Excel.Worksheet ws = null;

                s = file.Directory + "\\" + file.Name;
                lstr.Add(s);

                wb = xlApp.Workbooks.Open(lstr[filecount]);
                ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
                Excel.Range range;
                range = ws.UsedRange;

                rCnt = range.Rows.Count;
                cCnt = range.Columns.Count;

                for (rCnt = 1; rCnt <= rc; rCnt++)
                {
                    for (cCnt = 1; cCnt <= cc; cCnt++)
                    {
                        s = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
                    }
                }

                wb.SaveAs(@"D:\T01052\Programs\C#\Programs\Excel into Excel\Excel into Excel\Excel into Excel\Excel file\Outpoot File\Output.xlsx");

                wb.Close(true, null, null);
                xlApp.Quit();

                Marshal.ReleaseComObject(xlApp);
                Marshal.ReleaseComObject(wb);
                Marshal.ReleaseComObject(ws);

                filecount = filecount + 1;
                foreach (Process clsProcess in Process.GetProcesses())
                {
                    if (clsProcess.ProcessName.Equals("EXCEL"))
                    {
                        clsProcess.Kill();
                    }
                }
            }
        }

0 个答案:

没有答案