我試圖用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