5

如何获取 excel 工作簿中的第一行并使用 .net c# 将其保存到新的 excel 工作簿中?我不知道列的数量,所以需要获取整行。这是我所拥有的,但新工作簿是空白的(没有复制行)

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);
4

2 回答 2

3

试试这个代码:

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

或者

xlWorksheetNew.get_Range("A1", "A1").EntireRow.Value = xlWorksheet.get_Range("A1", "A1").EntireRow.Value;
于 2012-09-13T03:33:43.947 回答
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)
    {
    }
}

编辑:

我打算进入低级的东西,但不知道你的专业水平。如果您想要良好的性能,请不要使用复制/粘贴。在这里,我将向您展示一些性能技巧。首先一次写入所有单元格:

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

//在这里填充值,然后一举将数据写入Excel:

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

其次注意.WithComCleanup()- 在进行 VSTO 编码时,您需要注意管理非托管内存 - http://jake.ginnivan.net/vsto-com-interop

于 2012-09-13T03:59:04.557 回答