My question is, is there any other way to use my program apart from registering Interop dll on target machine?
你問,如果有任何的方式來使用你的程序,它使用的Excel互操作,當運行程序的計算機上沒有安裝Excel。最簡潔的答案是不。較長的答案是肯定的,如果你願意重構你的程序不使用互操作。
如果您要定向的Excel版本是2007及更高版本,則可以使用Microsoft提供的OOXml SDK。如果您願意花一點錢,也可以使用第三方庫,如Aspose。
使用OOXml SDK將電子表格插入Excel文件的示例可在msdn找到。
// Given a document name, inserts a new worksheet.
public static void InsertWorksheet(string docName)
{
// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
}
}
感謝您的詳細信息。我理解向OpenXML轉變的原因,但遺憾的是,由於其他原因,我不得不再次參與互操作。爲了解決這個問題,我爲我的程序安裝了excel(作爲先決條件)。 – Mahender