How do I merge multiple excel files to a single excel file

后端 未结 3 1418
情话喂你
情话喂你 2021-01-23 13:26

So I was trying to make an excel sheet aggregator. In my line of work we get people who send us a bunch of individual excel files that are all related each with only 1 sheet use

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-23 13:58

    In your inner loop you add a new worksheet to your 'finalized' workbook ('sheet') AND copy a worksheet before it for every source sheet. So every 'sheet' created by your Add command will be empty as in fact you create two sheets for each source sheet. Another problem is, that - as you mentioned - arrays in excel are 1-based; so you have to loop until j <= count not j < count.

    So I think that code would work better:

    Excel.Worksheet dummy = finalized.Worksheets[1];
    
    for (int i = 2; i <= excel.Workbooks.Count; i++)
    {
        int count = excel.Workbooks[i].Worksheets.Count;
    
        for (int j = 1; j <= count; j++)
        {
            Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
            pastee.Copy(dummy);
        }
    }
    
    dummy.Delete();
    

提交回复
热议问题