gpt4 book ai didi

c# - 将 Excel.WorkSheets 放入同一个 Excel.Workbook

转载 作者:行者123 更新时间:2023-11-30 18:36:32 25 4
gpt4 key购买 nike

因此,经过大量研究并在类中使用下面的代码后,我传递的项目(数据表)在 Excel 中打开。我有大约 5 张需要在同一本书中打开。下面的代码适用于前 2 个。问题是它们都在 NEW WorkBooks 中打开——我需要它们全部在 SAME WorkBook 中打开。不过,它们在每个新工作簿中的正确工作表上打开。我认为一个简单的“if”语句会起作用,然而,它不是——非常感谢任何有关如何将它们合并到一本工作簿中的意见,并提前致谢!

Microsoft.Office.Interop.Excel.Application oExcel = new               
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;


oExcel.Visible = true;
oExcel.DisplayAlerts = false;
oExcel.Application.SheetsInNewWorkbook = 5;
oBooks = oExcel.Workbooks;

oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
oSheets = oBook.Worksheets;

if (sheetName == "Combined")
{

oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
oSheet.Name = sheetName;

object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];


for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}


Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1, dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);


range.Value2 = arr;
}
else if (sheetName == "Auto")
{

oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(2);
oSheet.Name = sheetName;
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];


for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}


Microsoft.Office.Interop.Excel.Range c1 =
(Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 =
(Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1,
dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);


range.Value2 = arr;
}

最佳答案

好吧,如果没有注释,您的代码有点太长了,但如果您想在当前工作簿中添加一个新工作表,可以使用 myWorkbook.Sheets.Add() 方法(其中 myWorkbook 是对当前工作簿的引用).

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.sheets.add(v=office.14).aspx

关于c# - 将 Excel.WorkSheets 放入同一个 Excel.Workbook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13647141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com