object paths;
MSWord.Application wordApp;//Word应用程序变量
MSWord.Document wordDoc;//Word文档变量
string title = "这个是标题.doc";
paths = path + "\\" + title;
string pathname = path + "\\" + title;
wordApp = new MSWord.Application();//初始化
if (File.Exists((string)pathname))
{
File.Delete((string)pathname);
}
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
wordApp.Selection.ParagraphFormat.LineSpacing = 20f;//设置文档的行间距
wordDoc.Paragraphs.Last.Range.Font.Size = 16;
wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
string strContent = "这个是标题2 \n";
wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行缩进的长度
wordDoc.Paragraphs.Last.Range.Text = strContent;
wordDoc.Paragraphs.Last.Range.Font.Size = 12;
wordDoc.Paragraphs.Last.Range.Font.Bold = 0;
wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref unite, ref Nothing);
strContent = "基本信息 \n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
strContent = "基本描述 \n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Text = strContent;
wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
string picpath = "图片地址";
string pathHZ = Path.GetExtension(picpath);
//string path1 = Path.ChangeExtension(picpath, "ALK");
if (pathHZ == ".jpg" || pathHZ == ".png" || pathHZ == ".bmp")
{
wordApp.Selection.EndKey(ref unite, ref Nothing);
//定义要向文档中插入图片的位置
object range = wordDoc.Paragraphs.Last.Range;
//定义该图片是否为外部链接
object linkToFile = false;//默认
//定义插入的图片是否随word一起保存
object saveWithDocument = true;
//向word中写入图片
wordDoc.InlineShapes.AddPicture(picpath, ref linkToFile, ref saveWithDocument, ref range);
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片
wordDoc.Content.InsertAfter("\n");
//todo:此处添加图片名称并设置居中
strContent = "图" + (pic_number++) + " " + Path.GetFileNameWithoutExtension(picpath) + "\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
wordDoc.Paragraphs.Last.Range.Font.Size = 12;
wordDoc.Paragraphs.Last.Range.Font.Bold = 0;
wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
}
object format = MSWord.WdSaveFormat.wdFormatDocument;
wordDoc.SaveAs(ref paths, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
编辑内容时,注意要加换行符\n
C# 导出word(可设置文档格式,加载图片)
最新推荐文章于 2021-10-25 16:59:12 发布