如何获取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);
答案 0 :(得分:2)
试试这段代码:
xlWorksheetNew.get_Range("A1", "A1").EntireRow.Value = xlRangeHeader.Value;
或
xlWorksheetNew.get_Range("A1", "A1").EntireRow.Value = xlWorksheet.get_Range("A1", "A1").EntireRow.Value;
答案 1 :(得分: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。