Tag: Office SDK CSharp OpenXMLSDK
.NetFrameworkを使ってdocxファイルなどを作成するSDK。
namespace OpenXMLDemo { class Program { static void Main(string[] args) { using (var package = WordprocessingDocument.Create( "test.docx", WordprocessingDocumentType.Document)) { MainDocumentPart mainDocumentPart1 = package.AddMainDocumentPart(); Document document1 = new Document(); Body body1 = new Body(); Paragraph paragraph1 = new Paragraph(); Run run1 = new Run(); run1.Append(new Text() { Text = "a+b=c" }); paragraph1.Append(run1); body1.Append(paragraph1); document1.Append(body1); mainDocumentPart1.Document = document1; } } } }
class Program { private static String stylePath = @"d:\WordOpenXMLFormatSample\NewStylePart\styles.xml"; private static String packagePath = @"d:\WordOpenXMLFormatSample\SampleWordDocument.docx.zip"; private static void CopyStream(Stream source, Stream target) { const int bufSize = 0x1000; // const int bufSize = 1024; byte[] buf = new byte[bufSize]; int bytesRead = 0; while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) { target.Write(buf, 0, (int)bytesRead); } source.Close(); target.Close(); } static void SwapStylePart(String packagePath, String stylePath) { using (Package package = Package.Open(packagePath, FileMode.Open, FileAccess.ReadWrite)) { Uri uriPartTarget = new Uri("/word/styles.xml", UriKind.Relative); package.DeletePart(uriPartTarget); PackagePart packagePartReplacement = package.CreatePart(uriPartTarget, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"); using (FileStream fileStream = new FileStream(stylePath, FileMode.Open, FileAccess.Read)) { // Load the new styles.xml using a stream. CopyStream(fileStream, packagePartReplacement.GetStream()); } } } static void Main(string[] args) { SwapStylePart(packagePath, stylePath); } }