使用C#对LibreOffice表格的读取写入

首先将LibreOffice提供的5个dll导入到项目中

cli_basetypes

cli_cppuhelper

cli_oootypes

cli_ure

cli_uretypes

源代码

using System;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.table;
using uno.util;
using uno;

namespace Common
{
	public class LibreOffice : IDisposable
	{
		public XComponentContext xComponent { get; private set; }
		public XMultiServiceFactory ServiceManager { get; private set; }
		public XComponentLoader Desktop { get; private set; }
		public XSpreadsheetDocument Document { get; private set; }
		public XCellRangesAccess Sheet { get; private set; }
		public string URL { get; private set; }
		public bool success { get; private set; }

		/// <summary>
using System;

namespace Common
{
	class Test
	{
		public int main()
		{
			using(LibreOffice libre = new LibreOffice("D:/1.ods"))
			{
				//在A1格子中写入"hello world"
				libre.WriteCell(0,0,0,"hello world");
				
				//保存写入数据
				libre.Save();
			}
		}
	}
}

/// 创建一个 LibreOffice 类并与文件 path 连接/// </summary>/// <param name="filepath">文件地址</param>public LibreOffice(string filepath){if(!filepath.StartsWith("file:///")){URL = "file:///" + filepath;}success = Connent();}/// <summary>/// 向单元格写入字符串/// </summary>/// <param name="nColumn">列</param>/// <param name="nRow">行</param>/// <param name="nSheet">页</param>/// <param name="content">写入的内容</param>/// <param name="alignment">横向对齐方式:居左0,居右1,居中3</param>/// <param name="fontname">字体名字</param>/// <param name="fontHeight">字体大小</param>/// <param name="bold">加粗,这个加粗并非真正意义上的加粗,且无法还原</param>/// <param name="italic">斜体,未实现</param>/// <param name="underline">下划线,未实现</param>/// <returns>写入成功返回true</returns>public bool WriteCell(int nColumn, int nRow, int nSheet, string content, Int16? alignment = null, string fontname = null, float? fontHeight = null,bool? bold = null, bool? italic = null, bool? underline = null){if (!success || Sheet.getCellByPosition(nColumn, nRow, nSheet).getError() != 0){return false;}Sheet.getCellByPosition(nColumn, nRow, nSheet).setFormula(content);Int16 int16type = 0;int inttype = 0;float floattype = 0;string stringtypr = "";Any any = new Any();if (alignment != null){int16type = alignment ?? 0;any.setValue(int16type.GetType(), int16type);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("ParaAdjust", any);}if (fontname != null){stringtypr = fontname;any.setValue(stringtypr.GetType(), stringtypr);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("CharFontName", any);}if (fontHeight != null){floattype = fontHeight ?? 0;any.setValue(floattype.GetType(), floattype);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("CharHeight", any);}if (bold == true){inttype = 2;any.setValue(inttype.GetType(), inttype);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("VertJustify", any);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("HoriJustify", any);}//else if (bold == false)//{// inttype = 0;// any.setValue(inttype.GetType(), inttype);// ((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("VertJustify", any);// ((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("HoriJustify", any);//}return true;}/// <summary>/// 向单元格写入数字/// </summary>/// <param name="nColumn">列</param>/// <param name="nRow">行</param>/// <param name="nSheet">页</param>/// <param name="content">写入的内容</param>/// <param name="alignment">横向对齐方式:居左0,居右1,居中3</param>/// <param name="fontname">字体名字</param>/// <param name="fontHeight">字体大小</param>/// <param name="bold">加粗,这个加粗并非真正意义上的加粗,且无法还原</param>/// <param name="italic">斜体,未实现</param>/// <param name="underline">下划线,未实现</param>/// <returns>写入成功返回true</returns>public bool WriteCell(int nColumn, int nRow, int nSheet, double content, Int16? alignment = null,string fontname = null, float? fontHeight = null,bool? bold = null, bool? italic = null, bool? underline = null){if (!success || Sheet.getCellByPosition(nColumn, nRow, nSheet).getError() != 0){return false;}Sheet.getCellByPosition(nColumn, nRow, nSheet).setValue(content);Int16 int16type = 0;//int inttype = 0;float floattype = 0;string stringtypr = "";Any any = new Any();if (alignment != null){int16type = alignment ?? 0;any.setValue(int16type.GetType(), int16type);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("ParaAdjust", any);}if (fontname != null){stringtypr = fontname;any.setValue(stringtypr.GetType(), stringtypr);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("CharFontName", any);}if (fontHeight != null){floattype = fontHeight ?? 0;any.setValue(floattype.GetType(), floattype);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("CharHeight", any);}if (bold == true){int16type = 2;any.setValue(int16type.GetType(), int16type);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("VertJustify", any);((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("HoriJustify", any);}//else if (bold == false)//{// int16type = 0;// any.setValue(int16type.GetType(), int16type);// ((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("VertJustify", any);// ((XPropertySet)Sheet.getCellByPosition(nColumn, nRow, nSheet)).setPropertyValue("HoriJustify", any);//}return true;}/// <summary>/// 读取单元格内容/// </summary>/// <param name="nColumn">列</param>/// <param name="nRow">行</param>/// <param name="nSheet">页</param>/// <returns>读取的内容</returns>public string ReadCellFormula(int nColumn, int nRow, int nSheet){if (!success || Sheet.getCellByPosition(nColumn, nRow, nSheet).getError() != 0){return null;}return Sheet.getCellByPosition(nColumn, nRow, nSheet).getFormula(); ;}/// <summary>/// 读取单元格数字/// </summary>/// <param name="nColumn">列</param>/// <param name="nRow">行</param>/// <param name="nSheet">页</param>/// <returns>读取的内容</returns>public double? ReadCellValue(int nColumn, int nRow, int nSheet){if (!success || Sheet.getCellByPosition(nColumn, nRow, nSheet).getError() != 0){return null;}return Sheet.getCellByPosition(nColumn, nRow, nSheet).getValue(); ;}/// <summary>/// 保存文件/// </summary>/// <returns>成功返回true</returns>public bool Save(){if(!success || URL == ""){return false;}PropertyValue MyStruct = new PropertyValue();MyStruct.Name = "Hidden";MyStruct.Value = new Any(true);PropertyValue[] VariantArray = new PropertyValue[] { MyStruct, new PropertyValue() };((XStorable)Document).storeAsURL(URL, VariantArray);return true;}/// <summary>/// 合并单元格/// </summary>/// <param name="nLeft">左</param>/// <param name="nTop">上</param>/// <param name="nRight">右</param>/// <param name="nBottom">下</param>/// <param name="nSheet">页</param>public void MergeCell(int nLeft, int nTop, int nRight, int nBottom, int nSheet){if(((XMergeableCellRange)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).isMergeable()){return;}((XMergeableCellRange)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).merge();}/// <summary>/// 合并单元格/// </summary>/// <param name="aRange">范围,例:B1:C3 或者 $B$2</param>/// <param name="nSheet">页</param>public void MergeCell(string aRange, int nSheet){if (((XMergeableCellRange)Sheet.getCellRangesByName(aRange)[nSheet]).isMergeable()){return;}((XMergeableCellRange)Sheet.getCellRangesByName(aRange)[nSheet]).merge();}/// <summary>/// 设置边框/// </summary>/// <param name="nLeft">左</param>/// <param name="nTop">上</param>/// <param name="nRight">右</param>/// <param name="nBottom">下</param>/// <param name="nSheet">页</param>/// <param name="LeftBorder">左边框</param>/// <param name="TopBorder">上边框</param>/// <param name="RightBorder">右边框</param>/// <param name="BottomBorder">下边框</param>public void SetCheek(int nLeft, int nTop, int nRight, int nBottom, int nSheet,bool LeftBorder = true, bool TopBorder = true, bool RightBorder = true, bool BottomBorder = true){BorderLine border1 = new BorderLine(0, 0, 0, 0);BorderLine border2 = new BorderLine(65536, 0, 10, 0);Any any1 = new Any();any1.setValue(border1.GetType(), border1);Any any2 = new Any();any2.setValue(border2.GetType(), border2);if (LeftBorder){((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("LeftBorder", any2);}else{((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("LeftBorder", any1);}if (TopBorder){((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("TopBorder", any2);}else{((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("TopBorder", any1);}if (RightBorder){((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("RightBorder", any2);}else{((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("RightBorder", any1);}if (BottomBorder){((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("BottomBorder", any2);}else{((XPropertySet)Sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom, nSheet)).setPropertyValue("BottomBorder", any1);}}/// <summary>/// 设置边框/// </summary>/// <param name="aRange">范围,例:B1:C3 或者 $B$2</param>/// <param name="nSheet">页</param>/// <param name="LeftBorder">左边框</param>/// <param name="TopBorder">上边框</param>/// <param name="RightBorder">右边框</param>/// <param name="BottomBorder">下边框</param>public void SetCheek(string aRange, int nSheet,bool LeftBorder = true, bool TopBorder = true, bool RightBorder = true, bool BottomBorder = true){BorderLine border1 = new BorderLine(0, 0, 0, 0);BorderLine border2 = new BorderLine(65536, 0, 10, 0);Any any1 = new Any();any1.setValue(border1.GetType(), border1);Any any2 = new Any();any2.setValue(border2.GetType(), border2);if (LeftBorder){((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("LeftBorder", any2);}else{((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("LeftBorder", any1);}if (TopBorder){((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("TopBorder", any2);}else{((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("TopBorder", any1);}if (RightBorder){((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("RightBorder", any2);}else{((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("RightBorder", any1);}if (BottomBorder){((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("BottomBorder", any2);}else{((XPropertySet)Sheet.getCellRangesByName(aRange)[nSheet]).setPropertyValue("BottomBorder", any1);}}/// <summary>/// 关闭文件/// </summary>public void Close(){if(!success){return;}//如果只是一般函数出了问题,是可以Close的,如果是文件被删除了,是不能执行的,所以加了一层trytry{((unoidl.com.sun.star.util.XCloseable)Document).close(true);}catch { }success = false;}#region 内部使用函数/// <summary>/// 连接 libreoffice 文件/// </summary>/// <returns>连接成功返回true</returns>private bool Connent(){try{xComponent = Bootstrap.bootstrap();if (xComponent == null){return false;}ServiceManager = (XMultiServiceFactory)xComponent.getServiceManager();Desktop = (XComponentLoader)ServiceManager.createInstance("com.sun.star.frame.Desktop");PropertyValue MyStruct = new PropertyValue();MyStruct.Name = "Hidden";MyStruct.Value = new Any(true);PropertyValue[] VariantArray = new PropertyValue[] { MyStruct, new PropertyValue() };Document = (XSpreadsheetDocument)Desktop.loadComponentFromURL(URL, "_blank", 0, VariantArray);Sheet = (XCellRangesAccess)Document.getSheets();}catch{return false;}return true;}void IDisposable.Dispose(){Close();//throw new NotImplementedException();}#endregion}}源代码中存在部分未实现的功能

这部分功能对我本身没什么用,只是好看23333333333333333


代码使用

using System;

namespace Common
{
	class Test
	{
		public int main()
		{
			using(LibreOffice libre = new LibreOffice("D:/1.ods"))
			{
				//在A1格子中写入"hello world"
				libre.WriteCell(0,0,0,"hello world");
				
				//保存写入数据
				libre.Save();
			}
		}
	}
}


猜你喜欢

转载自blog.csdn.net/weixin_39868880/article/details/80513815