首先
下载Open XML SDK
安装后会有 DocumentFormat.OpenXml.dll ,项目中需引用。
下载的时候将 OpenXMLSDKTool.msi 也勾上一并下载,安装后会有反编译器 OpenXmlSdkTool.exe
可以帮助编写代码
如图:
写了一些封装数据的类,部分代码
class ReportType
{
public bool IsTitle;
public int Aligment = -1;//-1 左 0中 1右
public static PageHeadersOrFooters PageHeaders = null; //页眉
public static PageHeadersOrFooters PageFooters = null;//页脚
}
class PageHeadersOrFooters:List
{
public bool ExcludeFirstPage;//第一页是否有页眉页脚
public bool HavePageNum;//有无页码
}
class ReportText: ReportType //文本
{
public string Text;
public bool IsHead;
public float Size = 10;
public bool IsBold;
public bool IsItalic;
public bool IsUnderline;
private Dictionary<int, float> DicHeadSize = new Dictionary<int, float>() { { 1, 16f }, { 2, 14 }, { 3, 12 } };
public ReportText(bool isTitle,string text,float size=10)
{
Text = text;
IsTitle = isTitle;
Size = size;
IsBold = true;
}
public ReportText(string text,bool isHead,int HeadSize=1)
{
Text = text;
IsHead = isHead;
Size = DicHeadSize[HeadSize];
IsBold = true;
}
public ReportText(string text,float size = 10,bool isBold = false, bool isItalic = false, bool isUnderline = false)
{
Text = text;
IsBold = isBold;
IsItalic = isItalic;
IsUnderline = isUnderline;
Size = size;
}
}
class ReportImage:ReportType//图片
{
public string Path;
public string RId;
public int Width;
public int Height;
public ReportImage(string path,int width=500,int height=300)
{
Path = path;
Width = width;
Height = height;
}
}
生成报表的方法
public void Create()
{
try
{
if (string.IsNullOrEmpty(FileName))
return;
using (WordprocessingDocument doc = WordprocessingDocument.Create(FileName, WordprocessingDocumentType.Document))
{
#region
ExtendedFilePropertiesPart extendedFilePropertiesPart1 = doc.AddNewPart();
GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);
MainDocumentPart objMainDocumentPart = doc.AddMainDocumentPart();
objMainDocumentPart.Document = GetDocument();
DocumentSettingsPart documentSettingsPart1 = objMainDocumentPart.AddNewPart();
GenerateDocumentSettingsPart1Content(documentSettingsPart1);
StylesWithEffectsPart stylesWithEffectsPart1 = objMainDocumentPart.AddNewPart();
GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1);
StyleDefinitionsPart styleDefinitionsPart1 = objMainDocumentPart.AddNewPart();
GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);
ThemePart themePart1 = objMainDocumentPart.AddNewPart();
GenerateThemePart1Content(themePart1);
FontTablePart fontTablePart1 = objMainDocumentPart.AddNewPart();
GenerateFontTablePart1Content(fontTablePart1);
WebSettingsPart webSettingsPart1 = objMainDocumentPart.AddNewPart();
GenerateWebSettingsPart1Content(webSettingsPart1);
#endregion
SectionProperties sectionProperties = new SectionProperties();
objMainDocumentPart.Document = new Document();
objMainDocumentPart.Document.AppendChild(new Body());
Body body = doc.MainDocumentPart.Document.Body;
// PageSize pageSize = new PageSize();
// PageMargin pageMargin = new PageMargin();
// GetPageSetting(ref pageSize, ref pageMargin);
foreach (ReportType rt in ReportTypeList)
{
if (rt is ReportTable)//表格
{
ReportTable reportTable = rt as ReportTable;
body.Append(GetTable(reportTable));
}
if (rt is ReportText)//文本
{
ReportText reportText = rt as ReportText;
body.Append(GetParagraph(reportText));
}
if (rt is ReportImage)//图片
{
ReportImage reportImage = rt as ReportImage;
CreateImageRid(reportImage, objMainDocumentPart);
body.Append(GetParagraph(reportImage));
}
}
body.Append(sectionProperties);
if (ReportType.PageHeaders!=null)
{
AddHeader(objMainDocumentPart, ReportType.PageHeaders);//页眉
}
if(ReportType.PageFooters!=null)
{
AddFooters(objMainDocumentPart, ReportType.PageFooters);//页脚
}
objMainDocumentPart.Document.Save();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
创建文本段落部分
public Paragraph GetParagraph(ReportType repType)
{
Paragraph p = new Paragraph();
//给段落加段落属性
ParagraphProperties pPr = GetParagraphProperties(repType);
p.Append(pPr);
//run 表示一段内容
Run run = new Run();
if (repType is ReportText)
{
ReportText repText = repType as ReportText;
RunProperties rP = GetRunProperties(repText);
run.Append(rP);
//给run加文本
run.Append(new Text(repText.Text));
// 给段落加一段内容
}
if(repType is ReportImage)
{
ReportImage repImage= repType as ReportImage;
run = GetImageRun(repImage);
}
p.Append(run);
return p;
}
简单来说就是
1. body.Append(Paragraph())
2. Paragraph.Append(new Run())
3. Run.Append(new Text())
这么一个包含关系,当中有各种属性可以添加。
如果写入下面的数据
static void Main(string[] args)
{
List reportTypeList = new List();
PageHeadersOrFooters pageHeaders = new PageHeadersOrFooters();
pageHeaders.Add(new ReportText("页眉右") { Aligment = 1 });
pageHeaders.ExcludeFirstPage = true;
ReportType.PageHeaders = pageHeaders;
PageHeadersOrFooters pageFooters = new PageHeadersOrFooters();
pageFooters.Add(new ReportText("页脚左") { Aligment = -1 });
pageFooters.HavePageNum = true;
ReportType.PageFooters = pageFooters;
ReportText reportText = new ReportText(true, "Report", 20);//Title
reportTypeList.Add(reportText);
reportText = new ReportText("表格", true, 1);
reportTypeList.Add(reportText);
DataTable dt = new DataTable();
dt.Columns.Add("name", Type.GetType("System.String"));
dt.Columns.Add("sex", Type.GetType("System.String"));
dt.Columns.Add("age", Type.GetType("System.Int32"));
dt.Rows.Add("张三", "男", "22");
dt.Rows.Add("李四", "男", "28");
dt.Rows.Add("王二", "男", "30");
ReportTable reportTable = new ReportTable();
reportTable.PackTable(dt);
reportTypeList.Add(reportTable);
reportTypeList.Add(new ReportText(""));//空行
reportText = new ReportText("图片", true, 1);
reportTypeList.Add(reportText);
reportText = new ReportText("图片1", true, 2);
reportTypeList.Add(reportText);
string path = System.Environment.CurrentDirectory;
DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\..\", path));
ReportImage reportImage = new ReportImage(Path.Combine(di.FullName, "images\\image1.jpg"));
reportTypeList.Add(reportImage);
reportText = new ReportText("图片2", true, 2);
reportTypeList.Add(reportText);
reportImage = new ReportImage(Path.Combine(di.FullName, "images\\image2.jpg"));
reportTypeList.Add(reportImage);
WordOpenXml word = new WordOpenXml(reportTypeList);
word.FileName = Path.Combine(System.Environment.CurrentDirectory, "test.docx");
word.Create();
}
生成的word如下
生成表格,图片,页眉,页脚的代码较多,可以下载代码来看。