如何将 datagridview 导出到 Open Office Excel c# 中
本文关键字:Office Open Excel datagridview | 更新日期: 2023-09-27 18:34:23
我有一个datagridview,我可以将其导出到Excel Microsoft。现在我想将数据网格视图导出到 Open Office Excel。我无法弄清楚哪些程序集将用于我的 Open Office 项目的参考。对于Microsoft Excel,我使用了以下参考,后跟事件代码。
using Excel=Microsoft.Office.Interop.Excel;
private void exportToMSExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from .net app";
for (int i = 1; i < datagridEC.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = datagridEC.Columns[i - 1].HeaderText;
}
for (int i = 0; i < datagridEC.Rows.Count; i++)
{
for (int j = 0; j < datagridEC.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = datagridEC.Rows[i].Cells[j].Value.ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR--> " + ex.Message.ToString(), "ERROR");
}
finally
{
}
}
这适用于Microsoft Office,但现在我想将其替换为Open Office Excel。
您需要为以下程序集添加引用:cli_basetype、cli_cppihelper、cli_oootypes、cli_ure cli_uretypes
而且
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.beans;
using UNO = unoidl.com.sun.star.uno;
using OOo = unoidl.com.sun.star;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.table;
还有如何获取工作表的示例:
UNO.XComponentContext context = uno.util.Bootstrap.bootstrap();
XMultiServiceFactory SrvManager = (XMultiServiceFactory)context.getServiceManager();
XComponentLoader loader = (XComponentLoader)SrvManager.createInstance("com.sun.star.frame.Desktop");
string AFile = "file:///" + "filePath";
PropertyValue[] props = new PropertyValue[0];
XComponent oDoc = loader.loadComponentFromURL(AFile, "_blank", 0, props);
XSpreadsheetDocument xSpreadDoc = (XSpreadsheetDocument)oDoc;
XSpreadsheets xSheets = xSpreadDoc.getSheets();
XIndexAccess xIA = (XIndexAccess)xSheets;
XSpreadsheet xSheet = (XSpreadsheet)xIA.getByIndex(0).Value;