问题描述
我正在编写一个处理 Excel 文件的应用程序.我需要一个功能来删除工作表.我必须使用程序集 Microsoft.Office.Interop.Excel.dll.
I'm writing an application which works with excel files.I need a feature to delete a sheet.I have to use an assembly Microsoft.Office.Interop.Excel.dll.
它在开发者机器上运行良好,但是当我尝试将它部署到服务器上时出现错误:
It's running fine on developer machine but when I try to deploy it on server I'm getting an error:
无法加载文件或程序集 'office,版本 = 14.0.0.0,Culture=neutral, PublicKeyToken=71e9bce111e9429c' 或其中之一依赖
我了解当计算机上未安装 MS Office 时会出现问题.客户不想不惜任何代价在服务器上安装和购买 MS Office.
I understand that problem occurs when MS Office is not installed on a machine.Customer don't want to install and buy MS Office on a server not at any price.
我按照此处的建议在开发人员机器上安装了可再发行主互操作程序集":http://forums.asp.net/t/1530230.aspx/1并再次编译我的项目.
I install "Redistributable Primary Interop Assemblies" on developer machine as advised here: http://forums.asp.net/t/1530230.aspx/1and compile my project again.
代码示例:
public bool DeleteSheet(string tableName)
{
Excel.Application app = null;
Excel.Workbooks wbks = null;
Excel._Workbook _wbk = null;
Excel.Sheets shs = null;
bool found = false;
try
{
app = new Excel.Application();
app.Visible = false;
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
wbks = app.Workbooks;
_wbk = wbks.Add(xlsfile);
shs = _wbk.Sheets;
int nSheets = shs.Count;
for (int i = 1; i <= nSheets; i++)
{
Excel._Worksheet _iSheet = (Excel._Worksheet)shs.get_Item(i);
if (_iSheet.Name == tableName)
{
_iSheet.Delete();
found = true;
Marshal.ReleaseComObject(_iSheet);
break;
}
Marshal.ReleaseComObject(_iSheet);
}
if (!found)
throw new Exception(string.Format("Table "{0}" was't found", tableName));
_wbk.SaveAs(connect, _wbk.FileFormat, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
finally
{
_wbk.Close(null, null, null);
wbks.Close();
app.Quit();
Marshal.ReleaseComObject(shs);
Marshal.ReleaseComObject(_wbk);
Marshal.ReleaseComObject(wbks);
Marshal.ReleaseComObject(app);
}
return true;
}
例外
使用 CLSID 检索组件的 COM 类工厂{00024500-0000-0000-C000-000000000046}由于以下原因失败错误:80040154 类未注册(来自 HRESULT 的异常:0x80040154 (REGDB_E_CLASSNOTREG)).
发生在线
app = new Excel.Application();
谁能就如何使此功能成功运行提供建议?
Can anyone advise on how to get this feature working successfully?
推荐答案
如果没有安装 ms office,您将无法使用 Microsoft.Office.Interop.Excel.
You can't use Microsoft.Office.Interop.Excel without having ms office installed.
只需在google中搜索一些库,即可修改xls或xlsx:
Just search in google for some libraries, which allows to modify xls or xlsx:
- http://code.google.com/p/excellibrary/
- http://simpleooxml.codeplex.com/ (only xlsx)
这篇关于如何在没有安装 MS Office 的机器上使用 Microsoft.Office.Interop.Excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!