使用 Open.XML.SDK.无需 Office)生成WORD格式文档
步骤 1:安装 NuGet 包
Install-Package DocumentFormat.OpenXml
步骤 2:编写生成代码
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
//引用类库DocumentFormat.OpenXml
namespace HdhCmsCodeSaveToWord
{
public class WordGenerator
{
public void CreateWordDocument(string filePath)
{
try
{
SaveFileDialog saveHdhCms = new SaveFileDialog();
saveHdhCms.Title = "保存WORD文档";
saveHdhCms.Filter = "保存WORD文档(*.docx)|*.docx";
saveHdhCms.FileName = filePath;
if (saveHdhCms.ShowDialog() == DialogResult.OK)
{
filePath = saveHdhCms.FileName;
using (WordprocessingDocument doc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
// 添加主文档部件
MainDocumentPart mainPart = doc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
// 添加标题
Paragraph title = new Paragraph();
Run titleRun = title.AppendChild(new Run());
titleRun.AppendChild(new Text("员工信息报告"));
titleRun.RunProperties = new RunProperties(new RunFonts { Ascii = "黑体" }, new FontSize { Val = "32" });
body.AppendChild(title);
// 添加表格
Table table = new Table();
// 设置表格宽度为页面宽度的 50%
TableProperties tableProperties = new TableProperties(
new TableWidth
{
Width = "5000", // 50% → 5000 (50 * 100)
Type = TableWidthUnitValues.Pct
}
);
table.AppendChild(tableProperties);
TableGrid grid = new TableGrid();
int tableTotalWidthDxa = 11906 / 2;
// 定义多列宽度
grid.Append(
new GridColumn() { Width = ((int)(tableTotalWidthDxa * 0.3)).ToString() }, // 第一列宽度
new GridColumn() { Width = ((int)(tableTotalWidthDxa * 0.3)).ToString() }, // 第二列宽度
new GridColumn() { Width = ((int)(tableTotalWidthDxa * 0.4)).ToString() } // 第三列宽度
);
table.Append(grid); // 将列宽配置添加到表格
DocumentFormat.OpenXml.Wordprocessing.TableRow headerRow = new TableRow();
// 表头
headerRow.Append(
CreateCell("姓名", 1),
CreateCell("职位", 1),
CreateCell("入职日期", 1)
);
table.AppendChild(headerRow);
// 数据行
TableRow dataRow = new TableRow();
dataRow.Append(
CreateCell("张三", 0),
CreateCell("工程师", 0),
CreateCell(DateTime.Now.ToString("yyyy-MM-dd"), 0)
);
table.AppendChild(dataRow);
body.AppendChild(table);
// 添加段落用于存放图片
Paragraph paragraph = new Paragraph();
Run run = new Run();
// 加载图片并生成 Drawing 对象
Drawing drawing = CreateImageDrawing(doc, mainPart, "E:\\NewProject\\HltkQuotationApp\\HltkQuotationApp\\upload\\test02.png");
run.AppendChild(drawing);
paragraph.AppendChild(run);
body.AppendChild(paragraph);
mainPart.Document.Save();
//using(FileStream fs=new FileStream(filePath, FileMode.Open))
//{
// byte[] bt = new byte[fs.Length];
// string fileExt = Path.GetExtension(filePath);
// fs.Read(bt, 0, bt.Length);
//}
}
MessageBox.Show("文档生成成功!" + filePath);
}
}
catch (Exception ex)
{
MessageBox.Show($"生成失败:{ex.Message}");
}
}
// 创建表格单元格
private TableCell CreateCell(string text, int isHeader)
{
TableCell cell = new TableCell();
Paragraph para = new Paragraph();
Run run = new Run();
run.AppendChild(new Text(text));
if (isHeader == 1)
{
run.RunProperties = new RunProperties(new Bold());
}
para.AppendChild(run);
cell.AppendChild(para);
return cell;
}
private Drawing CreateImageDrawing(WordprocessingDocument doc, MainDocumentPart mainPart, string imagePath)
{
// 读取图片流
using (FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
{
// 根据图片格式选择 ImagePartType(如 Jpeg、Png)
PartTypeInfo imageType = GetImagePartType(Path.GetExtension(imagePath));
ImagePart imagePart = mainPart.AddImagePart(imageType);
// 将图片数据写入 ImagePart
imagePart.FeedData(imageStream);
Image image = Image.FromFile(imagePath);
int widthPx = image.Width;
int heightPx = image.Height;
double dpi = image.HorizontalResolution; // 或通过 image.HorizontalResolution 获取实际 DPI
long widthEmu = (long)(widthPx * 914400 / dpi);
long heightEmu = (long)(heightPx * 914400 / dpi);
//// 定义图片尺寸(单位:EMU)
//long widthEmu = 600 * 9525; // 600像素(假设 DPI=96,1像素=9525 EMU)
//long heightEmu = 400 * 9525; // 400像素
// 生成绘图对象
return new Drawing(
new DW.Inline(
new DW.Extent { Cx = widthEmu, Cy = heightEmu },
new DW.EffectExtent { LeftEdge = 0, TopEdge = 0, RightEdge = 0, BottomEdge = 0 },
new DW.DocProperties { Id = 1, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties { Id = 0, Name = "Image1" },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
{
Embed = doc.MainDocumentPart.GetIdOfPart(imagePart) // 绑定图片部件
},
new A.Stretch(new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset { X = 0, Y = 0 },
new A.Extents { Cx = widthEmu, Cy = heightEmu }),
new A.PresetGeometry(
new A.AdjustValueList())
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{ DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 }
);
}
}
// 根据文件扩展名确定 ImagePartType
private PartTypeInfo GetImagePartType(string fileExtension)
{
switch (fileExtension.ToLower())
{
case ".jpg":
case ".jpeg":
return ImagePartType.Jpeg;
case ".png":
return ImagePartType.Png;
case ".bmp":
return ImagePartType.Bmp;
case ".gif":
return ImagePartType.Gif;
default:
throw new NotSupportedException($"不支持的文件格式: {fileExtension}");
}
}
}
}
步骤 3:点击按钮调用
private void button1_Click(object sender, EventArgs e)
{
WordGenerator generator = new WordGenerator();
string path = (Application.StartupPath + "\\upload\\").ToLower().Replace("\\bin\\debug\\","\\");
if(!Directory.Exists(path))Directory.CreateDirectory(path);
generator.CreateWordDocument($"{path}Report.docx");
}
查看更多关于使用 Open.XML.SDK.无需 Office)生成WORD格式文档的详细内容...