准备工作使用Office导出Word:
1. 添加引用COM里面的 Microsoft Word 12.0 Object. Library 引用(12.0表示Word 2007版本)
2. 导命名空间
using MSWord =Microsoft.Office.Interop.Word;
3. 把引用中的Microsoft.Office.Interop.Word的“属性”中的嵌入互操作设为False
使用wps导出Word只需要替换com和更改引用命名空间
public string ToWord()
{
var serverPathS = Path.Combine(_webhostenvironment.ContentRootPath, AppConfigurtaion.Configuration["AppSettings:UploadFolder"]);
string path = Path.Combine(serverPathS, "BG");//文件路径变量
var filepath = ComFun.CreateWord(path);
return filepath;
}
生成Word方法
public static string CreateWord(string serverPath)
{
try
{
if (System.IO.Directory.Exists(serverPath) == false)//如果不存在就创建文件夹
{
System.IO.Directory.CreateDirectory(serverPath);
}
string dateTime = "报告" + "_" + DateTime.Now.ToString("yyyyMMddhhmmss");
object path = System.IO.Path.Combine(serverPath, dateTime + ".doc");
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//创建document对象
XWPF.XWPFDocument doc = new XWPF.XWPFDocument();
//创建段落对象
XWPF.XWPFParagraph p1 = doc.CreateParagraph();
p1.Alignment = XWPF.ParagraphAlignment.CENTER;
XWPF.XWPFRun runTitle = p1.CreateRun();
runTitle.IsBold = true;
runTitle.SetText("这是一个word文档");
runTitle.FontSize = 16;
runTitle.SetFontFamily("宋体", XWPF.FontCharRange.None);//设置雅黑字体
XWPF.XWPFParagraph p2 = doc.CreateParagraph();
XWPF.XWPFRun run1 = p2.CreateRun();
run1.SetText(" 这是第一行文字");
run1.FontSize = 12;
run1.SetFontFamily("华文楷体", XWPF.FontCharRange.None);//设置雅黑字体
string fileName = string.Format("{0}.doc", DateTime.Now.ToString("yyyyMMdd"), System.Text.Encoding.UTF8);
FileStream fs = new FileStream(Path.Combine(serverPath, fileName), FileMode.Create);
doc.Write(fs);
fs.Close();
return path.ToString();
}
catch
{
return "";
}
}