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);
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With