1.直接将Html转成Word。MVC自带FileResult很好用。Html中我们也可以嵌入自己的样式。

html:

<div id="target">
<style>
table{border-collapse: collapse;border: 1px solid black;}
td{border: 1px royalblue solid}
</style>
<img src="../../Content/eman_sm.png" alt="" />
<table>
<tr>
<td>姓名</td>
<td>成绩</td>
</tr>
<tr>
<td>张山</td>
<td>80分</td>
</tr>
<tr>
<td>李四</td>
<td>90分</td>
</tr>
</table>
</div>
<div style="color: red"></div>
<a id="ea" href="#">导出word</a>
<a href="@Url.Action("ExportWords")">ExportWords</a>
<script>
$("#ea").click(function () {
var html = $("#target").html();
window.open("/Home/ExportWord?html=" + html);
})
</script>

get方法会受到url长度的影响,可以换成隐藏的form提交。

<form id="form1" action="/Home/ExportWord">
<input type="hidden" value="" name="html" id="cc" />
<input type="submit" id="st" />
</form>
<div id="target">
<style>
table{border-collapse: collapse;border: 1px solid black;}
td{border: 1px royalblue solid}
</style>
<table>
<tr>
<td>姓名</td>
<td>成绩</td>
</tr>
<tr>
<td>张山</td>
<td>80分</td>
</tr>
<tr>
<td>李四</td>
<td>90分</td>
</tr>
</table>
</div>
<div style="color: red"></div>
<a id="ea" href="#">导出word</a>
<a href="@Url.Action("ExportWords")">ExportWords</a>
<script>
$("#ea").click(function () {
var html = $("#target").html();
$("#cc").val(html);
$("#st").click();
})
</script>

Action:

 [ValidateInput(false)]
public FileResult ExportWord(string html)
{
StringBuilder sb = new StringBuilder();
sb.Append("<!DOCTYPE html>");
sb.Append("<body>");
sb.Append(html);
sb.Append("</body>");
var byteArray = System.Text.Encoding.Default.GetBytes(sb.ToString());
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
return File(byteArray, "application/ms-word", "wordtest" + ".doc");
}

这样的问题是导出的图片是引用型的,路径一变化就不会显示了。优点就是速度很快。

2.使用Microsoft.Office.Interop.Word 提供的方法创建一个word。

    /// <summary>
/// 创建一个word
/// </summary>
/// <returns></returns>
public ActionResult ExportWords()
{
CreateAWord();
SetPageHeader("测试创建一个Word文档");
InsertText("这是一个测试文档的内容", , WdColor.wdColorGray10, , WdParagraphAlignment.wdAlignParagraphLeft);
NewLine();
InsertPicture(@"C:\Users\Administrator\Desktop\duoceshi.png");
InsertTable();
SaveWord(@"C:\Users\Administrator\Desktop\\test.doc");
CloseDocument(@"C:\Users\Administrator\Desktop\\test.doc");
return null;
}
/// <summary>
/// Word应用对象
/// </summary>
private Microsoft.Office.Interop.Word.Application _wordApplication;
/// <summary>
/// word 文件对象
/// </summary>
private Microsoft.Office.Interop.Word.Document _wordDocument;
/// <summary>
/// 创建文档 如果报错:类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数 ; 解决方法:在其中点开“引用”文件夹,在"Microsoft.Office.Interop.Word" 上点击鼠标右键,选择“属性”,将属性中的“嵌入互操作类型”的值改为“false”即可
/// </summary>
public void CreateAWord()
{
//实例化word应用对象
this._wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
Object myNothing = System.Reflection.Missing.Value;
this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
}
/// <summary>
/// 添加页眉
/// </summary>
/// <param name="pPageHeader"></param>
public void SetPageHeader(string pPageHeader)
{
//添加页眉
this._wordApplication.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
this._wordApplication.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
this._wordApplication.ActiveWindow.ActivePane.Selection.InsertAfter(pPageHeader);
//设置中间对齐
this._wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
//跳出页眉设置
this._wordApplication.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
}
/// <summary>
/// 插入文字
/// </summary>
/// <param name="pText">文本信息</param>
/// <param name="pFontSize">字体大小</param>
/// <param name="pFontColor">字体颜色</param>
/// <param name="pFontBold">字体粗体</param>
/// <param name="ptextAlignment">方向</param>
public void InsertText(string pText, int pFontSize, Microsoft.Office.Interop.Word.WdColor pFontColor, int pFontBold, Microsoft.Office.Interop.Word.WdParagraphAlignment ptextAlignment)
{
//设置字体样式以及方向
this._wordApplication.Application.Selection.Font.Size = pFontSize;
this._wordApplication.Application.Selection.Font.Bold = pFontBold;
this._wordApplication.Application.Selection.Font.Color = pFontColor;
this._wordApplication.Application.Selection.ParagraphFormat.Alignment = ptextAlignment;
this._wordApplication.Application.Selection.TypeText(pText);
}
/// <summary>
/// 换行
/// </summary>
public void NewLine()
{
//换行
this._wordApplication.Application.Selection.TypeParagraph();
}
/// <summary>
/// 插入一个图片
/// </summary>
/// <param name="pPictureFileName"></param>
public void InsertPicture(string pPictureFileName)
{
object myNothing = System.Reflection.Missing.Value;
//图片居中显示
this._wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
this._wordApplication.Application.Selection.InlineShapes.AddPicture(pPictureFileName, ref myNothing, ref myNothing, ref myNothing);
}
/// <summary>
/// 插入表格
/// </summary>
public void InsertTable()
{
object myNothing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Table table1 = _wordDocument.Tables.Add(_wordApplication.Selection.Range, , , ref myNothing, ref myNothing);
_wordDocument.Tables[].Cell(, ).Range.Text = "产品\n项目";
_wordDocument.Tables[].Cell(, ).Range.Text = "电脑";
_wordDocument.Tables[].Cell(, ).Range.Text = "手机";
_wordDocument.Tables[].Cell(, ).Range.Text = "重量(kg)";
_wordDocument.Tables[].Cell(, ).Range.Text = "价格(元)";
_wordDocument.Tables[].Cell(, ).Range.Text = "共同信息";
_wordDocument.Tables[].Cell(, ).Range.Text = "信息A";
_wordDocument.Tables[].Cell(, ).Range.Text = "信息B";
table1.Select();
table1.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中 _wordApplication.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
_wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
_wordApplication.Selection.Cells.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
_wordApplication.Selection.Cells.Height = ;
table1.Rows[].Height = ;
table1.Rows[].Height = ;
table1.Rows[].Height = ;
table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
_wordApplication.Selection.Cells.Width = ;
table1.Columns[].Width = ;
table1.Cell(, ).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
table1.Cell(, ).Range.Paragraphs[].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; _wordApplication.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
_wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
_wordApplication.Selection.Cells.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
_wordApplication.Selection.Cells.Height = ;
table1.Rows[].Height = ; table1.Rows[].Height = ;
table1.Rows[].Height = ;
table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
_wordApplication.Selection.Cells.Width = ;
table1.Columns[].Width = ;
table1.Cell(, ).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
table1.Cell(, ).Range.Paragraphs[].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; //表头斜线
table1.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible = true;
table1.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
table1.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt; //表格边框
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Visible = true;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible = true;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible = true;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble; table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Visible = true;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble; //合并单元格
//_wordDocument.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));
}
[DllImport("shell32.dll ")]
public static extern int ShellExecute(IntPtr hwnd, String lpszOp, String lpszFile, String lpszParams, String lpszDir, int FsShowCmd);
/// <summary>
/// 关闭文档
/// </summary>
public void CloseDocument(string fileName)
{
object myNothing = System.Reflection.Missing.Value;
//关闭文档
object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; _wordDocument.Close(ref myNothing, ref myNothing, ref myNothing);
_wordApplication.Application.Quit(ref saveOption, ref myNothing, ref myNothing); _wordDocument = null; _wordApplication = null;
//ShellExecute(IntPtr.Zero, "open", fileName, "", "", 3);
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="pFileName">文件名</param>
public void SaveWord(string pFileName)
{
object myNothing = System.Reflection.Missing.Value;
object myFileName = pFileName;
object myWordFormatDocument = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
object myLockd = false;
object myPassword = "";
object myAddto = true;
try
{
this._wordDocument.SaveAs(ref myFileName, ref myWordFormatDocument, ref myLockd, ref myPassword,
ref myAddto, ref myPassword,
ref myLockd, ref myLockd, ref myLockd, ref myLockd, ref myNothing, ref myNothing, ref myNothing,
ref myNothing, ref myNothing, ref myNothing);
}
catch (Exception exception)
{
throw new Exception("保存word文档失败!");
}
}

图片倒是保存住了,可配置的地方很多,速度有些慢,代码量颇多。

3.如果要导出excel 还是用NPOI最好。 http://www.cnblogs.com/lwme/archive/2011/11/18/npoi_excel_import_export.html

调用该博主ExcelRender中的方法,返回File。 不然网上的其他办法都很有问题,要么打不开,要么服务器没装office就不行了。

 public FileResult ExportExcel()
{
DataTable table = new DataTable();
table.Columns.Add("aa", typeof(string));
table.Columns.Add("bb", typeof(string));
table.Columns.Add("cc", typeof(string));
for (int i = ; i < ; i++)
{
string a = DateTime.Now.Ticks.ToString();
Thread.Sleep();
string b = DateTime.Now.Ticks.ToString();
Thread.Sleep();
string c = DateTime.Now.Ticks.ToString();
Thread.Sleep();
table.Rows.Add(a, b, c);
} var ms= ExcelRender.RenderToExcel(table); return File(ms, "application/vnd.ms-excel", "考试成绩.xls");
}

4. Excel导入。

file就是一个HttpPostedFileBase 对象。即上传的excel文件。用ExcelRender 转换为table 再进行插入数据库的操作。

   byte[] filebBytes =new byte[file.ContentLength];
file.InputStream.Read(filebBytes, , file.ContentLength); var table = ExcelRender.RenderFromExcel(new MemoryStream(filebBytes),,);

【吉光片羽】MVC 导出Word的两种方式的更多相关文章

  1. (转)DLL中导出函数的两种方式(dllexport与.def文件)

    DLL中导出函数的两种方式(dllexport与.def文件)http://www.cnblogs.com/enterBeijingThreetimes/archive/2010/08/04/1792 ...

  2. 【转】DLL中导出函数的两种方式(dllexport与.def文件)

    DLL中导出函数的两种方式(dllexport与.def文件) DLL中导出函数的声明有两种方式: 一种方式是:在函数声明中加上__declspec(dllexport):另外一种方式是:采用模块定义 ...

  3. dll导出函数的两种方式的比较

    最初的网页链接已经挂了, 在此贴一个中间的转载链接 https://blog.csdn.net/zhazhiqiang/article/details/51577523 一 概要 vs中导出 dll的 ...

  4. DLL中导出函数的两种方式(dllexport与.def文件)

    DLL中导出函数的声明有两种方式: 一种方式是:在函数声明中加上__declspec(dllexport): 另外一种方式是:采用模块定义(.def)文件声明,(.def)文件为链接器提供了有关被链接 ...

  5. DLL声明导出函数的两种方式

    DLL中导出函数的声明有两种方式:一种为在函数声明中加上__declspec(dllexport):另外一种方式是采用模块定义(.def) 文件声明,.def文件为链接器提供了有关被链接程序的导出.属 ...

  6. java导出word的6种方式(复制来的文章)

    来自: http://www.cnblogs.com/lcngu/p/5247179.html 最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前 ...

  7. [转载]java导出word的5种方式

    在网上找了好多天将数据库中信息导出到word中的解决方案,现在将这几天的总结分享一下.总的来说,java导出word大致有5种解决方案: 1:Jacob是Java-COM Bridge的缩写,它在Ja ...

  8. [原创]java导出word的5种方式

    在网上找了好多天将数据库中信息导出到word中的解决方案,现在将这几天的总结分享一下.总的来说,java导出word大致有5种解决方案: 1:Jacob是Java-COM Bridge的缩写,它在Ja ...

  9. java导出word的6种方式(转发)

    来自: http://www.cnblogs.com/lcngu/p/5247179.html 最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前 ...

随机推荐

  1. Ceph剖析:线程池实现

    线程池ThreadPool的实现符合生产者-消费者模型,这个模型解除生产者消费者间的耦合关系,生产者可以专注处理制造产品的逻辑而不用关心产品的消费,消费者亦然.当然,生产者消费者之间需要一个连接的纽带 ...

  2. 122. Best Time to Buy and Sell Stock(二) leetcode解题笔记

    122. Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price ...

  3. Android(Xamarin)之旅(五)

    2016年1月23日,北京迎来了很痛苦的一天,冻死宝宝了,一天都没有出我自己的小黑屋,在这屋子里自娱自乐.不知道你们呢 对于android的四大基本组件(Activity.Service.Broadc ...

  4. ibatis 参数错误,无效字符

    --- The error occurred in EmptyMapping.xml. --- The error occurred while applying a parameter map. - ...

  5. C#高级--通过类来理解学习委托

    namespace classanddelegate { class Program { static void Main(string[] args) { //这是类的实例化 Test test = ...

  6. 【java】:常用工具类

    PS; 平时用到的一些工具类,验证非空.字符切割.时间转换.金额转换 package com.jws.common.util; import java.io.UnsupportedEncodingEx ...

  7. 第四章 使用Docker镜像和仓库(二)

    第四章 使用Docker镜像和仓库(二) 回顾: 开始学习之前,我先pull下来ubuntu和fedora镜像 [#9#cloudsoar@cloudsoar-virtual-machine ~]$s ...

  8. 读Windows核心编程-5-作业

    作业(Job) 有时候需要把一些进程集中管理,如终止一个进程以及它产生的子进程,但由于Windows并没有维护进程间父子关系,所以除非进程本身以某种方式记录这些信息,否则很难做到管理这种父子进程树.而 ...

  9. ios 的touch事件分析

    IOS之触摸事件和手势   13.1 事件概述 13.2 触摸事件 13.3 手势 13.1 事件概述 事件是当用户手指触击屏幕及在屏幕上移动时,系统不断发送给应用程序的对象. 系统将事件按照特定的路 ...

  10. Java打jar包详细教学

    如果我们需要将写好并测试OK的公共接口供多个项目使用,我们可以不用拷贝源代码,可以编译后打包成jar文件,这样会很方便许多,修改的话也方便,直接修改源代码打一个新jar包替换即可,下面是打包的详细教程 ...