Copy the first row to an excel workbook in a new Excel workbook

How to get the first row in an Excel workbook and save it in a new Excel workbook using .net C #? I do not know the number of columns, so you need to get the whole row. This is what I have, but the new workbook is empty (without copying the lines)

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
source share
2 answers

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
source
 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 low-level material, but did not know your level of knowledge. If you need good performance, do not use Copy / Paste. Here I will show you a couple of simple tricks. First write to all cells at once:

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

// Fill in the values ​​here, and then write the data in Excel in one fell swoop:

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

Secondly, pay attention to .WithComCleanup() - when encoding VSTO, you need to know about unmanaged memory management - http://jake.ginnivan.net/vsto-com-interop .

+2
source

Source: https://habr.com/ru/post/1433927/


All Articles