导出word文档(无模版):

using Microsoft.Office.Interop.Word;

        public static string CreateWordFile(CaseVM model,string path)
{
string message = "";
try
{
Object Nothing = System.Reflection.Missing.Value;
//Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录
//string name = "CNSI_" + DateTime.Now.ToLongDateString() + ".doc";
object filename = path; //文件保存路径
//创建Word文档
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //添加页眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[国泰安理财规划大赛案例]");
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置右对齐
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距 //移动焦点并换行
object count = ;
object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 // 插入段落
Microsoft.Office.Interop.Word.Paragraph para;
para = WordDoc.Content.Paragraphs.Add(ref Nothing); para.Range.Text = "案例信息";
//para.Range.Font.Size = 20;
para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorRed;
para.Range.Font.Italic = ;
para.Range.InsertParagraphAfter();
//WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 para.Range.Text = "客户姓名:" + model.CustomerName;
//para.Range.Font.Size = 12;
para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorBlack;
para.Range.Font.Italic = ;
para.Range.InsertParagraphAfter(); para.Range.Text = "身份证号:" + model.IDNum;
para.Range.InsertParagraphAfter(); para.Range.Text = "理财类型:" + model.strFinancialType;
para.Range.InsertParagraphAfter(); para.Range.Text = "客户背景:" + model.CustomerStory;
para.Range.InsertParagraphAfter(); WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 para.Range.Text = "考核点";
para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorRed;
para.Range.Font.Italic = ;
para.Range.InsertParagraphAfter();
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorBlack;
para.Range.Font.Italic = ;
//文档中创建表格
Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, , , ref Nothing, ref Nothing);
//设置表格样式
newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[].Width = 50f;
newTable.Columns[].Width = 50f;
newTable.Columns[].Width = 160f;
newTable.Columns[].Width = 160f; //填充表格内容
newTable.Cell(, ).Range.Text = "序号";
newTable.Cell(, ).Range.Bold = ;//设置单元格中字体为粗体
//合并单元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
newTable.Cell(, ).Range.Text = "类型";
newTable.Cell(, ).Range.Bold = ;//设置单元格中字体为粗体
//合并单元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
newTable.Cell(, ).Range.Text = "考点";
newTable.Cell(, ).Range.Bold = ;//设置单元格中字体为粗体
//合并单元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
newTable.Cell(, ).Range.Text = "答案";
newTable.Cell(, ).Range.Bold = ;//设置单元格中字体为粗体
//合并单元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 int i = ;
foreach (var item in model.ExamPointAnswer)
{
i++;
//填充表格内容
newTable.Cell(i, ).Range.Text =(i-).ToString();
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(i, ).Range.Text = item.strExamType;
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(i, ).Range.Text = item.strExamPoint;
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(i, ).Range.Text = item.Answer;
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
} ////填充表格内容
//newTable.Cell(2, 1).Range.Text = "产品基本信息";
//newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
////合并单元格
//newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
//WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; ////填充表格内容
//newTable.Cell(3, 1).Range.Text = "品牌名称:";
//newTable.Cell(3, 2).Range.Text = "BrandName";
////纵向合并单元格
//newTable.Cell(3, 3).Select();//选中一行
//object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
//object moveCount = 5;
//object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
//WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
//WordApp.Selection.Cells.Merge();
////////插入图片
//////string FileName = @"c:\picture.jpg";//图片所在路径
//////object LinkToFile = false;
//////object SaveWithDocument = true;
//////object Anchor = WordDoc.Application.Selection.Range;
//////WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
//////WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
//////WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
////////将图片设置为四周环绕型
//////Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
//////s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; //newTable.Cell(12, 1).Range.Text = "产品特殊属性";
//newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
////在表格中增加行
//WordDoc.Content.Tables[1].Rows.Add(ref Nothing); //WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
//WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //文件保存
WordDoc.SaveAs(ref filename, 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, ref Nothing);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
//message = name + "文档生成成功,以保存到C:CNSI下";
}
catch
{
message = "文件导出异常!";
}
return message;
}

MS参照:http://www.cnblogs.com/haoxuan/articles/5135599.html

using Aspose.Words;

public static string CreateWordFile2(CaseVM model, string path)
{
string message = "";
try
{
Aspose.Words.Document doc = new Aspose.Words.Document();
DocumentBuilder builder = new DocumentBuilder(doc); builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Font.Color = Color.Blue;
builder.Font.Size = ;
builder.Write("[国泰安理财规划大赛案例]");
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; builder.MoveToDocumentStart();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Color = Color.Red;
builder.Font.Bold = true;
builder.Font.Italic = true;
builder.Writeln("案例信息");
builder.InsertBreak(BreakType.LineBreak); builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.Font.Italic = false;
builder.Writeln("客户姓名:" + model.CustomerName);
builder.Writeln("身份证号:" + model.IDNum);
builder.Writeln("理财类型:" + model.strFinancialType);
builder.Writeln("客户背景:" + model.CustomerStory);
builder.InsertBreak(BreakType.LineBreak); builder.Font.Color = Color.Red;
builder.Font.Bold = true;
builder.Font.Italic = true;
builder.Writeln("考核点");
builder.InsertBreak(BreakType.LineBreak);
builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.Font.Italic = false; builder.CellFormat.Borders.LineStyle = LineStyle.Single;
builder.CellFormat.Borders.Color = Color.Black; builder.InsertCell();
builder.Write("序号");
builder.InsertCell();
builder.Write("类型");
builder.InsertCell();
builder.Write("考点");
builder.InsertCell();
builder.Write("答案");
builder.EndRow(); int i = ;
foreach (var item in model.ExamPointAnswer)
{
i++;
builder.InsertCell();
builder.Write((i - ).ToString());
builder.InsertCell();
builder.Write(item.strExamType == null ? "" : item.strExamType);
builder.InsertCell();
builder.Write(item.strExamPoint == null ? "" : item.strExamPoint);
builder.InsertCell();
builder.Write(item.Answer == null ? "" : item.Answer);
builder.EndRow();
}
builder.EndTable();
doc.Save(path); }
catch
{
message = "文件导出异常!";
}
return message;
}

Aspose参照(含源码):http://blog.csdn.net/fraing/article/details/8989736

根据数据导出word文档(有模版):

Aspose参照:http://www.cnblogs.com/jingshuisihan/p/4604260.html

MS参照:http://bbs.csdn.net/topics/390946804?page=1

导入xls/xlsx到DataTable:

HSSFWorkbook: http://www.cnblogs.com/songrun/p/3547738.html

OLEDB:

HDR=Yes,这代表第一行是标题,不做为数据使用;IMEX ( IMport EXport mode )设置
  IMEX 有三种模式:
  0 is Export mode
  1 is Import mode
  2 is Linked mode (full update capabilities)
  我这里特别要说明的就是 IMEX 参数了,因为不同的模式代表著不同的读写行为:
  当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。
  当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。
  当 IMEX=2 时为“连结模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。

Aspose:

        /// <summary>
/// HSSFWorkbook读取xls
/// </summary>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
public static DataTable GetExcelToDataTableByNPOI(string filepath)
{
NPOI.HSSF.UserModel.HSSFWorkbook hssworkbook;
using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
hssworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(file);
}
ISheet sheet = hssworkbook.GetSheetAt();
IRow headerRow = sheet.GetRow();
int rowCount = sheet.LastRowNum;
int cellCount = headerRow.LastCellNum;
DataTable dt = new DataTable();
for (int j = ; j < cellCount; j++)
{
dt.Columns.Add(Convert.ToChar(((int)('A')) + j).ToString());
}
for (int r = (sheet.FirstRowNum + ); r <= rowCount; r++)
{
IRow row = sheet.GetRow(r); //读取当前行数据
if (row != null)
{
DataRow dr = dt.NewRow();
cellCount = row.LastCellNum;
bool isCellNull = true;
for (int i = ; i < cellCount; i++)
{
ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = "";
}
else
{
cell.SetCellType(NPOI.SS.UserModel.CellType.STRING);
dr[i] = cell.StringCellValue;
if (isCellNull)
{
if (!string.IsNullOrWhiteSpace(cell.StringCellValue))
{
isCellNull = false;
}
}
}
}
if (!isCellNull)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// OleDb读取xls/xlsx
/// </summary>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
public static DataTable GetExcelToDataTableByOleDb(string filepath)
{
string strCon = "";
if (filepath.IndexOf(".xlsx") != -)
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filepath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
else if (filepath.IndexOf(".xls") != -)
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; string strCom = " SELECT * FROM [Sheet1$]"; DataTable dt_temp = new DataTable();
using (OleDbConnection myConn = new OleDbConnection(strCon))
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
{
myConn.Open();
myCommand.Fill(dt_temp);
} return dt_temp;
} /// <summary>
/// Aspose读取xls/xlsx
/// </summary>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
public static DataTable GetExcelToDataTableByAspose(string filepath)
{
DataTable dt_temp = new DataTable();
try
{
Aspose.Cells.Workbook oBook = new Aspose.Cells.Workbook(filepath);
Cells cells = oBook.Worksheets[].Cells;
dt_temp = cells.ExportDataTable(, , cells.MaxDataRow + , cells.MaxColumn + );
}
catch (Exception ex)
{
}
return dt_temp;
}

C# 导出Word的更多相关文章

  1. java 导出word 并下载

    记录一下导出操作 源码: /************ * 导出word 并下载 * @param id 房号记录编号 * ***********************/ @RequestMappin ...

  2. Asp.net通过模板(.dot/Html)导出Word,同时导出图片

    一.Office组件导出Word(服务器配置麻烦) 需要引用Office的DLL,在下文的附件中,不同的Offic版本用的不一样,虽然高级版本可以兼容低级的,不过,还是统一版本最好 贴上核心代码(转载 ...

  3. 导出Excel And 导出word

      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx. ...

  4. 使用NPOI2.1.3.1版本导出word附带表格和图片

    原文:http://www.cnblogs.com/afutureBoss/p/4074397.html?utm_source=tuicool&utm_medium=referral 最近项目 ...

  5. Java使用velocity导出word

    效果展示: 使用word编辑好模板

  6. 【吉光片羽】MVC 导出Word的两种方式

    1.直接将Html转成Word.MVC自带FileResult很好用.Html中我们也可以嵌入自己的样式. html: <div id="target"> <st ...

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

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

  8. 【MVC】 非常简单的页面导出 WORD, EXCEL方法

    [MVC] 页面导出 WORD, EXCEL 前端 js function output() { var para = new Object(); para.html = getHtml(" ...

  9. 网页内容导出word/excel的js代码

    IE设置: 工具-> Internet选项-> 安全->自定义级别-> 对没有标记安全级别的ActiveX控件进行初始化  设为启用! 1.导出word //指定区域导出到Wo ...

  10. MVC4 导出word

    添加程序包 DocX using System.IO;using Novacode; /// <summary> /// 导出Word /// </summary> publi ...

随机推荐

  1. Google Adsense(Google网站联盟)广告申请指南

    Google AdSense 是一种获取收入的快速简便的方法,适合于各种规模的网站发布商.它可以在网站的内容网页上展示相关性较高的 Google 广告,并且这些广告不会过分夸张醒目.由于所展示的广告同 ...

  2. WinDBG调试.NET程序示例

    WinDBG调试.NET程序示例 好不容易把环境打好了,一定要试试牛刀.我创建了一个极其简单的程序(如下).让我们期待会有好的结果吧,阿门! using System; using System.Co ...

  3. Service Manager 2012

    部署Service Manager 2012遇到的2个问题 上周装了个Service Manager 2012学习,以便完善System Center整个解决方案,在部署期间遇到2个问题,花了我不少时 ...

  4. js中的AMD规范

    回首萧瑟,残月挂角,孤草弄影. 看了一下上一篇随笔的日期,距离上一篇日志又过去了许久.在这段时间中,我尽全力去拯救那间便利店,可惜到最后依然失败,这一次是所有的出路全部没有了,我也做了所有的努力.闲下 ...

  5. spring redis入门

    小二,上菜!!! 1. 虚拟机上安装redis服务 下载tar包,wget http://download.redis.io/releases/redis-2.8.19.tar.gz. 解压缩,tar ...

  6. gcc编译器优化给我们带来的麻烦???

    gcc编译器优化给我们带来的麻烦??? 今天看到一个很有趣的程序,如下: ? 1 2 3 4 5 6 7 8 9 int main() {     const int a = 1;     int * ...

  7. 我的Emacs折腾经验谈(一) 一些给新人的建议

    这几天都没有动力写mongodb的东西,我果然还是太懒了么~ 主要是没有一个系统的东西整理出来,加上我令人拙计的语言表达能力,这个坑只能慢慢再补了. 最近在折腾emacs这个东西,首先说我曾经算是个极 ...

  8. 输入参数能动态调决定调用哪个实现类 spring的一个特性

    今天做公司的以前项目的时候发现项目中有个特别好的东西,记录下来,分享一下 发现spring有个这样的功能,我也不知道这个是东西应该怎么称呼,就是通过输入参数,动态决定调用接口的实现类.简单理解就是在s ...

  9. 1.C#基础学习笔记3---C#字符串(转义符和内存存储无关)

    技术qq交流群:JavaDream:251572072  教程下载,在线交流:创梦IT社区:www.credream.com ------------------------------------- ...

  10. C++中const用法详解

    本文主要内容来自CSDN论坛: http://bbs.csdn.net/topics/310007610 我做了下面几点补充. 补充: 1. 用const声明全局变量时, 该变量仅在本文件内可见, 类 ...