我试图用C#中的工作表添加到现有的Excel实例,但我得到添加工作表到当前Excel工作簿
对象的错误不设置到对象的实例
抛出的这行代码是与newSheet =
开始我不知道这是为什么被抛出,因为我声明我的变量newSheet
,我已经实例化xlApp
之一----我需要做什么为了使这个语法按预期工作而改变?
public static void AddNewSheet()
{
Excel.Application xlApp;
xlApp = new Excel.Application();
Excel.Worksheet Jobs, Estimates;
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Test.xlsx";
var xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet newSheet;
//Add a new worksheet to the workbook
newSheet = (Excel.Worksheet)xlApp.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
}
编辑
附加代码 - 与加入已创建工作簿的工作表希望帮助。
namespace GenerateExcelWorkbookData
{
public partial class Form1 : Form
{
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Worksheet newSeet;
Main()
{
//Query Excel To Get DataTable Here
//Excel Info
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
CreateSubWorksheets();
}
public static void CreateSubWorksheets()
{
string sheetNameprefix = "SS";
Excel.Worksheet sheet1;
sheet1 = xlApp.ActiveWorkbook.Worksheets.Item["Newly Added"];
Excel.Range range = sheet1.Range["A1"].CurrentRegion;
object OriginalData = range.Value;
string OriginalAddress = range.Address;
while (range.Cells[2, 1].Value != null && range.Cells[2, 1].Value != "")
{
range.AutoFilter(1, range.Cells[2, 1].Value);
newSeet = (Excel.Worksheet)xlApp.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
//Do more stuff here
}
}
}
}
不能添加表那里。 WorkBook缺失... – A3006
@ A3006 - 它在我运行的不同C#项目中完美工作。 – BellHopByDayAmetuerCoderByNigh