Copy first row in excel workbook to a new excel workbook

青春壹個敷衍的年華 提交于 2021-02-07 14:52:14

问题


How do I get the first row in an excel workbook & save it to a new excel workbook using .net c#? I dont know the amount of columns so need to get entire row. This what I have but the new workbook is blank (no row copied)

Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file);    
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];    
Excel.Range xlRangeHeader = xlWorksheet.get_Range("A1", "A1").EntireRow;                         
Excel.Workbook xlWorkbookNew = xlApp.Workbooks.Add();    
Excel._Worksheet xlWorksheetNew = xlWorkbookNew.Sheets[1];    
xlWorksheetNew.get_Range("A1", "A1").EntireRow.Value = xlRangeHeader;                        
xlWorkbook.Close(false);                        
xlWorkbookNew.SaveAs(Path.Combine(sDestination, Path.GetFileName(file)), fileFormat);                        
xlWorkbookNew.Close(true);

回答1:


Try this code:

xlWorksheetNew.get_Range("A1", "A1").EntireRow.Value = xlRangeHeader.Value;        

or

xlWorksheetNew.get_Range("A1", "A1").EntireRow.Value = xlWorksheet.get_Range("A1", "A1").EntireRow.Value;



回答2:


public void test(Application xlApp)
{
    string file = @"C:\Temp\a.xlsx";
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    xlWorksheet.Range["A1"].EntireRow.Copy(); 
    Excel.Workbook xlWorkbookNew = xlApp.Workbooks.Add();
    Excel._Worksheet xlWorksheetNew = xlWorkbookNew.Sheets[1];
    Worksheet activeSheet = xlWorkbookNew.ActiveSheet;
    activeSheet.Paste();

    xlWorkbook.Close(false);
    xlWorkbookNew.SaveAs(Path.Combine(@"C:\Temp", Path.GetFileName(file)));
    xlWorkbookNew.Close(true);
    CloseExcel();
}

public void CloseExcel(Application xlApp)
{
    try
    {
        if (xlApp != null)
        {
            xlApp.Quit();
            if (Marshal.IsComObject(xlApp))
                Marshal.ReleaseComObject(xlApp);
        }
    }
    catch (Exception ex)
    {
    }
}

Edit:

I was going to get into the low level stuff but didn't know your level of expertise. If you want good performance dont use the Copy/Paste. Here I'll show you a couple of perf tricks. Firstly write to all cells at once:

object[,] values = (object[,])Array.CreateInstance(typeof(object), new int[2] { rowCount, ColumnCount }, new int[2] { 1, 1 });

//Populate the values here and then write the data to Excel in one fowl swoop:

using (var targetRange = xlApp.Range[topLeft + startRow + ":" + rightBottom + endRow].WithComCleanup())
{
   targetRange.Resource.Value2 = values;
}

Secondly notice the .WithComCleanup() - when doing VSTO coding you need to be aware of managing the unmanaged memory - http://jake.ginnivan.net/vsto-com-interop.



来源:https://stackoverflow.com/questions/12399010/copy-first-row-in-excel-workbook-to-a-new-excel-workbook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!