替换存储在表示Word/Excel文档的字节数组中的字符串 [英] Replacing strings stored in a byte array that represent Word/Excel document
问题描述
我将Word和Excel文档存储在SQL Server数据库表中.这些文档是使用C#应用程序从数据库中提取的,并放入 byte []
数组中.
I'm storing Word and Excel documents inside a SQL Server database table. These documents are pulled from the database with my C# application and are put into byte[]
arrays.
我想替换在Word/Excel文档中找到的某些字符串.使用可用字节数组的最佳方法是什么?
I want to replace certain strings found in the Word/Excel documents. What is the best way to do this with the byte array available?
我正在看这样的东西:
string fileString = System.Text.Encoding.UTF8.GetString(image.ImageObject);
fileString = fileString.Replace("FROM", "TO");
byte[] newImageObject = System.Text.Encoding.UTF8.GetBytes(fileString);
推荐答案
我建议您使用使用该库,您可以执行以下操作来替换Word文档中的文本,考虑到 documentByteArray
是您从数据库中获取的文档字节内容:
With the library, you can do the following to replace text from a Word document, considering that documentByteArray
is your document byte content taken from database:
using (MemoryStream mem = new MemoryStream())
{
mem.Write(documentByteArray, 0, (int)documentByteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
上面的示例摘自此处.您可以对Excel电子表格进行类似的处理.
The example above was taken from here. You can do similarly with Excel spreadsheets.
这篇关于替换存储在表示Word/Excel文档的字节数组中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!