如果开发的ASP.NET应用需要导出数据到word中的话,需要注意一点,就是导出按钮,建议不要使用button或者linkbutton在后代码中直接处理,最好使用ashx一般处理程序,或者是ajax异步处理一下,要不然后台处理的话,每次只能点击一次,不能重复导出,要刷新页面才可以,使用ashx或者ajax就可以保证重复点击导出都没有问题。
使用asp.net开发导出word格式的数据,如果是图片的话,需要先将图片下载到本地,然后从本地添加到word中,要不然你的文档拷贝到不能上网的地方就会出现红叉啊,路径问题。
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private string GetFilePath(string filepath)
{
string filename = filepath.Trim().Substring(filepath.LastIndexOf("/") + 1);
string result = string.Empty;
WebResponse response = null;
Stream stream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Settings.ImageRemoteDirectory +
filepath.Substring(filepath.IndexOf("..") + 2));
response = request.GetResponse();
stream = response.GetResponseStream();
if (!response.ContentType.ToLower().StartsWith("text/"))
{
result = SaveBinaryFile(response, filename);
}
}
catch { }
return result;
}
private string SaveBinaryFile(WebResponse response, string fileName)
{
string result = Settings.ImageLocalhostTempSaveDirectory + fileName;
byte[] buffer = new byte[1024];
try
{
if (File.Exists(result))
{
string name = string.Format("{0}{1}{2}{3}",
DateTime.Now.Minute, DateTime.Now.Minute, DateTime.Now.Millisecond, fileName);
result = Settings.ImageLocalhostTempSaveDirectory + name;
}
Stream outStream = File.Create(result);
Stream inStream = response.GetResponseStream();
int i;
do
{
i = inStream.Read(buffer, 0, buffer.Length);
if (i > 0) outStream.Write(buffer, 0, i);
} while (i > 0);
outStream.Close();
inStream.Close();
}
catch { }
return result;
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Word11.InlineShape inlineShape= wordTable.Cell(i, selectedColsIndex.IndexOf(j)+1).Range.InlineShapes.AddPicture(filepath , ref _missing, ref _missing,
ref _missing);
inlineShape.Width = 61;
inlineShape.Height = 80;
还有啊,需要设置服务器的DCOM,是的网络用户有权限启动word程序才可以,否则会出错,类似:
检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005
检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 8000401a 。
设置可以参考下面的网址
1、Asp.net 2.0在配置Microsoft Excel、Microsoft Word应用程序权限时 error: 80070005 和8000401a 的解决总
2007-11-01 11:30
检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。
控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Word文档
之后
单击属性打开此应用程序的属性对话框。
单击"安全"选项卡,分别在"启动和激活权限"和"访问权限"组中选中"自定义",然后
自定义->编辑->添加ASP.NET账户和IUSER_计算机名
* 这些帐户仅在计算机上安装有 IIS 的情况下才存在。
13. 确保允许每个用户访问,然后单击确定。
14. 单击确定关闭 DCOMCNFG。
检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 8000401a 。
运行dcomcnfg打开组件服务,
依次展开"组件服务"->"计算机"->"我的电脑"->"DCOM配置"
找到"Microsoft Excel应用程序"或"Microsoft Word应用程序",
右键打开属性对话框,点击"标识"选项卡,
点"下列用户",把管理员的用户密码正确填写进去...
点击"安全"选项卡,
依次把"启动和激活权限","访问权限","配置权限",都选择为自定义,
然后依次点击它们的编辑,把everyone添加进去,并加入所有的权限...
OK,解决此问题!
2、请设置web.config中的<identity impersonate="true" userName="administrator" password="51aspx"/>帐号和密码,否则会提示检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。
例如
<system.web>
<identity impersonate="true" userName="administrator" password="chuguo186"/>
</system.web>
文章出处:DIY部落(http://www.diybl.com/course/4_webprogram/asp.net/netjs/200824/98835.html)
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private void button1_Click(object sender, System.EventArgs e)
{
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
//Start Word and create a new document.
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
//Insert a paragraph at the beginning of the document.
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "Heading 1";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();
//Insert a paragraph at the end of the document.
Word.Paragraph oPara2;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Heading 2";
oPara2.Format.SpaceAfter = 6;
oPara2.Range.InsertParagraphAfter();
//Insert another paragraph.
Word.Paragraph oPara3;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
oPara3.Range.Font.Bold = 0;
oPara3.Format.SpaceAfter = 24;
oPara3.Range.InsertParagraphAfter();
//Insert a 3 x 5 table, fill it with data, and make the first row
//bold and italic.
Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
int r, c;
string strText;
for(r = 1; r <= 3; r++)
for(c = 1; c <= 5; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
oTable.Rows[1].Range.Font.Bold = 1;
oTable.Rows[1].Range.Font.Italic = 1;
//Add some text after the table.
Word.Paragraph oPara4;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara4.Range.InsertParagraphBefore();
oPara4.Range.Text = "And here's another table:";
oPara4.Format.SpaceAfter = 24;
oPara4.Range.InsertParagraphAfter();
//Insert a 5 x 2 table, fill it with data, and change the column widths.
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
for(r = 1; r <= 5; r++)
for(c = 1; c <= 2; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
oTable.Columns[2].Width = oWord.InchesToPoints(3);
//Keep inserting text. When you get to 7 inches from top of the
//document, insert a hard page break.
object oPos;
double dPos = oWord.InchesToPoints(7);
oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
do
{
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.ParagraphFormat.SpaceAfter = 6;
wrdRng.InsertAfter("A line of text");
wrdRng.InsertParagraphAfter();
oPos = wrdRng.get_Information
(Word.WdInformation.wdVerticalPositionRelativeToPage);
}
while(dPos >= Convert.ToDouble(oPos));
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
object oPageBreak = Word.WdBreakType.wdPageBreak;
wrdRng.Collapse(ref oCollapseEnd);
wrdRng.InsertBreak(ref oPageBreak);
wrdRng.Collapse(ref oCollapseEnd);
wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
wrdRng.InsertParagraphAfter();
//Insert a chart.
Word.InlineShape oShape;
object oClassType = "MSGraph.Chart.8";
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);
//Demonstrate use of late bound oChart and oChartApp objects to
//manipulate the chart object with MSGraph.
object oChart;
object oChartApp;
oChart = oShape.OLEFormat.Object;
oChartApp = oChart.GetType().InvokeMember("Application",
BindingFlags.GetProperty, null, oChart, null);
//Change the chart type to Line.
object[] Parameters = new Object[1];
Parameters[0] = 4; //xlLine = 4
oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
null, oChart, Parameters);
//Update the chart image and quit MSGraph.
oChartApp.GetType().InvokeMember("Update",
BindingFlags.InvokeMethod, null, oChartApp, null);
oChartApp.GetType().InvokeMember("Quit",
BindingFlags.InvokeMethod, null, oChartApp, null);
//
![](https://www.cnblogs.com/Images/dot.gif)
//Object model on the oChart and oChartApp objects to make additional
//changes to the chart.
//Set the width of the chart.
oShape.Width = oWord.InchesToPoints(6.25f);
oShape.Height = oWord.InchesToPoints(3.57f);
//Add text after the chart.
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.InsertParagraphAfter();
wrdRng.InsertAfter("THE END.");
//Close this form.
this.Close();
}
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kimbanx.UCS.ForeignStudentAdmin.Common
{
/// <summary>
/// 实用工具类
/// </summary>
public class KUtility
{
/// <summary>
/// 学生详表StudentDetailsTable的全部显示字段
/// </summary>
public static string StudentDetailsTableFieldsString = " 1-照片--2-姓名(中英全)--3-姓名(中英简)--4-职务--5-国家--6-文化程度--7-学号 " ;
/// <summary>
/// 学生详表StudentDetailsTable的隐藏字段HiddenField的value
/// </summary>
public static string StudentDetailsTableHiddenFieldValue = " 1-2-3-4-5-6-7 " ;
/// <summary>
/// 分割类似【1-姓名--2-年龄--3-工资】这样的字符串,将他们分割存放在字典中
/// </summary>
/// <param name="input"> 要分割的字符串 </param>
/// <param name="tokenGroup"> 组分隔符-- </param>
/// <param name="token"> 分隔符- </param>
/// <returns> Dictionary,键类型int,值类型string </returns>
public static Dictionary < int , string > Split( string input, string tokenGroup, string token)
{
List < int > list = new List < int > ();
Dictionary < int , string > dic = new Dictionary < int , string > ();
string [] strSplit = new string [] { tokenGroup };
string [] strSplit1 = new string [] { token };
string [] tokenGroups = input.Split(strSplit, StringSplitOptions.None);
string [] tokens = new string [ 2 ];
foreach ( string group in tokenGroups)
{
tokens = group.Split(strSplit1, StringSplitOptions.None);
dic.Add( int .Parse(tokens[ 0 ]), tokens[ 1 ]);
}
return dic;
}
/// <summary>
/// 将Dictionary,键类型int,值类型string,组成成一个类似【1-姓名--2-年龄--3-工资】这样的字符串
/// </summary>
/// <param name="dic"> Dictionary,键类型int,值类型string </param>
/// <returns> 类似【1-姓名--2-年龄--3-工资】这样的字符串 </returns>
public static string Combine(Dictionary < int , string > dic)
{
StringBuilder sb = new StringBuilder();
foreach ( int key in dic.Keys)
{
if (sb.Length == 0 )
{
sb.Append( string .Format( " {0}-{1} " , key.ToString(), dic[key]));
}
else
{
sb.Append( string .Format( " --{0}-{1} " , key.ToString(), dic[key]));
}
}
return sb.ToString();
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Word11 = Microsoft.Office.Interop.Word;
using System.IO;
using System.Data;
using System.Net;
using Kimbanx.UCS.ForeignStudentAdmin.Common;
using System.Text;
using System.Reflection;
namespace Kimbanx.UCS.ForeignStudentAdmin.UserControl
{
public class StudentDetailsTable_Word_V2
{
#region Variables
private string _strWordFilename = "" ;
private string _strWordFilepath;
private bool _wordVisible = false ;
private Word11.Application _oWord;
private Word11.Document _oDoc;
object _missing = System.Reflection.Missing.Value;
object _oEndOfDoc = " \\endofdoc " ;
#endregion
#region Properties
public Word11.Application OApplication
{
get { return _oWord; }
}
public Word11.Document ODoc
{
get { return _oDoc; }
}
public string WordFilename
{
get { return _strWordFilename; }
}
public string WordFilepath
{
get { return _strWordFilepath; }
}
#endregion
#region Constrctor
public StudentDetailsTable_Word_V2()
{
}
public StudentDetailsTable_Word_V2( string strFullFilepath)
{
_oWord.Visible = false ;
_strWordFilename = Path.GetFileName(strFullFilepath);
_strWordFilepath = Path.GetDirectoryName(strFullFilepath);
}
public StudentDetailsTable_Word_V2( string strFullFilepath, bool overwrite)
{
_strWordFilename = Path.GetFileName(strFullFilepath);
_strWordFilepath = Path.GetDirectoryName(strFullFilepath);
_oWord.Visible = _wordVisible;
if (overwrite || ! File.Exists(strFullFilepath))
{
}
else
{
this .Open(strFullFilepath);
}
}
#endregion
#region Method
public void Open( string strFilepath)
{
object filepath = strFilepath;
object wordVisible = _wordVisible;
object oMissing = System.Reflection.Missing.Value;
}
public void CreateWordFile()
{
_oWord = new Word11.Application();
_oDoc = _oWord.Documents.Add( ref _missing, ref _missing, ref _missing, ref _missing);
}
private void CreateWordFile( string strFullFillpath)
{
object ofilename = strFullFillpath;
_oDoc = _oWord.Documents.Add( ref _missing, ref _missing, ref _missing, ref _missing);
}
/// <summary>
/// 给文档插入标题
/// </summary>
/// <param name="document"></param>
/// <param name="range"></param>
/// <param name="title"></param>
public void InsertTitle(Word11.Document document, string title)
{
Word11.Paragraph oPara1;
oPara1 = document.Content.Paragraphs.Add( ref _missing);
oPara1.Range.Text = title;
oPara1.Range.Font.Size = 20 ;
oPara1.Range.Font.Bold = 0 ;
oPara1.Alignment = Word11.WdParagraphAlignment.wdAlignParagraphCenter;
oPara1.Format.SpaceAfter = 6 ;
oPara1.Range.InsertParagraphAfter();
}
/// <summary>
/// 给表格插入表头
/// </summary>
/// <param name="document"></param>
/// <param name="range"></param>
/// <param name="title"></param>
public void InsertTableTitle(Word11.Document document, Word11.Table table, List < int > list, Dictionary < int , string > tableTitle)
{
for ( int key = 0 ; key < tableTitle.Keys.Count; key ++ )
{
table.Cell( 1 , key + 1 ).Range.Text = tableTitle[list[key]];
}
table.Rows[ 1 ].Range.Font.Size = 15 ;
}
/// <summary>
/// word文档中插入表格
/// </summary>
/// <param name="document"></param>
/// <param name="range"></param>
/// <param name="rows"></param>
/// <param name="cols"></param>
public void InsertTableToWord(Word11.Document document, int rows, int cols)
{
Word11.Range range1 = document.Bookmarks.get_Item( ref _oEndOfDoc).Range;
Word11.Table table = document.Tables.Add(range1, rows, cols, ref _missing, ref _missing);
table.Range.ParagraphFormat.SpaceAfter = 6 ;
// 设置表格宽度,100%
table.PreferredWidthType = Word11.WdPreferredWidthType.wdPreferredWidthPercent;
table.PreferredWidth = 100 ;
// _oWord.Selection.ParagraphFormat.Alignment = Word11.WdParagraphAlignment.wdAlignParagraphCenter;
}
private string GetFilePath( string filepath)
{
string filename = filepath.Trim().Substring(filepath.LastIndexOf( " / " ) + 1 );
string result = string .Empty;
WebResponse response = null ;
Stream stream = null ;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Settings.ImageRemoteDirectory +
filepath.Substring(filepath.IndexOf( " .. " ) + 2 ));
response = request.GetResponse();
stream = response.GetResponseStream();
if ( ! response.ContentType.ToLower().StartsWith( " text/ " ))
{
result = SaveBinaryFile(response, filename);
}
}
catch { }
return result;
}
private string SaveBinaryFile(WebResponse response, string fileName)
{
string result = Settings.ImageLocalhostTempSaveDirectory + fileName;
byte [] buffer = new byte [ 1024 ];
try
{
if (File.Exists(result))
{
string name = string .Format( " {0}{1}{2}{3} " ,
DateTime.Now.Minute, DateTime.Now.Minute, DateTime.Now.Millisecond, fileName);
result = Settings.ImageLocalhostTempSaveDirectory + name;
}
Stream outStream = File.Create(result);
Stream inStream = response.GetResponseStream();
int i;
do
{
i = inStream.Read(buffer, 0 , buffer.Length);
if (i > 0 ) outStream.Write(buffer, 0 , i);
} while (i > 0 );
outStream.Close();
inStream.Close();
}
catch { }
return result;
}
public void SetPageMargin()
{
// 设置页面的四个边距
_oDoc.PageSetup.LeftMargin = 40f;
_oDoc.PageSetup.RightMargin = 40f;
_oDoc.PageSetup.TopMargin = 40f;
_oDoc.PageSetup.BottomMargin = 40f;
// 设置页面的高度和宽度,高度<宽度,使得页面是横板
_oDoc.PageSetup.PageHeight = 595.2756f ;
_oDoc.PageSetup.PageWidth = 841.8898f ;
}
/// <summary>
/// 将datatable中的数据插入到word中
/// datatable的行列都是从0开始的
/// gridview的列行都是从0开始
/// word中表格的行列都是从1开始的
/// 选中gridview的列从1开始
/// </summary>
/// <param name="wordTable"> word的表格 </param>
/// <param name="dataTable"> datatable数据 </param>
/// <param name="rows"> datatable数据的行数 </param>
/// <param name="cols"> gvStudent,GridView的列数,也就是页面上面的表格列数 </param>
/// <param name="selectedColsIndex"> 选中gridview的列编号,从1开始 </param>
public void InsertDataToWord(Word11.Table wordTable, DataTable dataTable,
int rows, int cols, List < int > selectedColsIndex)
{
DateTime datetime;
bool isDateTime = false ;
for ( int i = 2 ; i <= rows + 1 ; i ++ )
{
// wordTable.Rows.Add(ref afterRow);
wordTable.Rows[i].Range.Font.Size = 12 ;
for ( int j = 1 ; j <= cols; j ++ )
{
// dataTable column name
// " row_number,s.zpadress,s.xmqz,s.xmqy,s.xmjz,s.xmjy,s.jx,s.zw,s.gj,s.sjyqk,s.zj,s.csrq,s.rwrq,s.xzz,s.dhd,s.dhx,s.fcjp,s.xh"
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
if ( ! selectedColsIndex.Contains(j))
continue ;
switch (j)
{
case 1 :
string file = GetFilePath(dataTable.Rows[i - 2 ][j].ToString());
if ( string .IsNullOrEmpty(file)) continue ;
Word11.InlineShape inlineShape = wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.InlineShapes.AddPicture(file
, ref _missing, ref _missing,
ref _missing);
inlineShape.Width = 61 ;
inlineShape.Height = 80 ;
// _oWord.Selection.ParagraphFormat.Alignment = Word11.WdParagraphAlignment.wdAlignParagraphCenter;
break ;
case 2 :
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0}\n{1} " ,
dataTable.Rows[i - 2 ][j].ToString().Replace( " • " , " · " ),
dataTable.Rows[i - 2 ][j + 1 ].ToString());
break ;
case 3 :
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0}\n{1} " ,
dataTable.Rows[i - 2 ][j + 1 ].ToString().Replace( " • " , " · " ),
dataTable.Rows[i - 2 ][j + 2 ].ToString());
break ;
case 4 :
case 5 : case 6 :
case 7 :
case 8 :
isDateTime = DateTime.TryParse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 2 ].ToString()), out datetime);
if (isDateTime)
{
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text =
DateTime.Parse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 2 ].ToString())).ToShortDateString();
}
else
{
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 2 ].ToString());
}
break ;
case 9 :
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0}\n{1} " ,
DateTime.Parse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 2 ].ToString())).ToShortDateString(), DateTime.Parse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 3 ].ToString())).ToShortDateString());
break ;
case 10 :
isDateTime = DateTime.TryParse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 3 ].ToString()), out datetime);
if (isDateTime)
{
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text =
DateTime.Parse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 3 ].ToString())).ToShortDateString();
}
else
{
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 3 ].ToString());
}
break ;
case 11 :
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0}\n{1} " ,
dataTable.Rows[i - 2 ][j + 3 ].ToString(),
dataTable.Rows[i - 2 ][j + 4 ].ToString());
break ;
default :
isDateTime = DateTime.TryParse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 4 ].ToString()), out datetime);
if (isDateTime)
{
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text =
DateTime.Parse( string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 4 ].ToString())).ToShortDateString();
}
else
{
wordTable.Cell(i, selectedColsIndex.IndexOf(j) + 1 ).Range.Text = string .Format( " {0} " ,
dataTable.Rows[i - 2 ][j + 4 ].ToString());
}
break ;
}
}
}
#region
// for (int i = 2; i <= rows+1; i++)
// {
// for (int j = 1; j <= cols; j++)
// {
// switch (j)
// {
// case 1:
// wordTable.Cell(i, j).Range.InlineShapes.AddPicture(
// GetFilePath(dataTable.Rows[i - 2][j ].ToString()),ref _missing,ref _missing,
// ref _missing);
// break;
// case 2:
// wordTable.Cell(i, j).Range.Text = string.Format("{0}\n{1}",
// dataTable.Rows[i - 2][j ].ToString(), dataTable.Rows[i - 2][j+1].ToString());
// break;
// case 6:
// wordTable.Cell(i, j).Range.Text = string.Format("{0}\n{1}",
// dataTable.Rows[i - 2][j ].ToString(), dataTable.Rows[i - 2][j+1].ToString());
// break;
// default:
// wordTable.Cell(i, j).Range.Text = dataTable.Rows[i - 2][j].ToString();
// break;
// }
// }
// }
#endregion
}
public string Save( string filePath, string fileName)
{
string tempFile;
if ( string .IsNullOrEmpty(fileName))
tempFile = Guid.NewGuid().ToString();
else
tempFile = fileName;
tempFile = string .Format( " {0}{1}.doc " , filePath, tempFile);
object oDocFileName = tempFile;
object fileFormat = Word11.WdSaveFormat.wdFormatDocument;
_oDoc.SaveAs( ref oDocFileName, ref fileFormat, ref _missing, ref _missing, ref _missing
, ref _missing, ref _missing, ref _missing, ref _missing
, ref _missing, ref _missing, ref _missing, ref _missing
, ref _missing, ref _missing, ref _missing);
_oDoc.Close( ref _missing, ref _missing, ref _missing);
_oWord.Quit( ref _missing, ref _missing, ref _missing);
return tempFile;
}
public void Close()
{
try
{
_oWord.Application.Quit( ref _missing, ref _missing, ref _missing);
if (_oWord != null )
_oWord = null ;
}
catch { }
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
#endregion
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Kimbanx.UCS.ForeignStudentAdmin.Model;
using Kimbanx.UCS.ForeignStudentAdmin.Common;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using Microsoft.SharePoint;
namespace Kimbanx.UCS.ForeignStudentAdmin.UserControl._layouts
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = " http://tempuri.org/ " )]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class StudentDetailsTableWordHandler_V2 : IHttpHandler, IReadOnlySessionState
{
#region Fields
private DataTable _studentTable = null ;
private string selected;
private int pageIndex;
private int pageSize;
private string queryStringWhere;
private string studentType;
private string classCode;
private string fileName;
private int gvColCount;
private Dictionary < int , string > fieldsSelectedDic;
private List < int > fieldsSelected;
#endregion
#region Methods
private void GetRequestQueryString()
{
selected = HttpUtility.UrlDecode ( HttpContext.Current.Request.QueryString[ " selected " ]);
pageIndex = int .Parse(HttpContext.Current.Request.QueryString[ " pageIndex " ]);
pageSize = int .Parse(HttpContext.Current.Request.QueryString[ " pageSize " ]);
queryStringWhere = HttpContext.Current.Request.QueryString[ " queryStringWhere " ];
studentType = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString[ " studentType " ]);
classCode = HttpContext.Current.Request.QueryString[ " classCode " ];
gvColCount = int .Parse(HttpContext.Current.Request.QueryString[ " gvColCount " ]);
fileName = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString[ " fileName " ]);
GetFieldsSelected(selected);
}
private void GetFieldsSelected( string selected)
{
fieldsSelected = new List < int > ();
fieldsSelectedDic = new Dictionary < int , string > ();
string [] strSplit = new string [] { " -- " };
string [] tokenGroup = selected.Split(strSplit, StringSplitOptions.None);
string [] token = new string [ 2 ];
foreach ( string group in tokenGroup)
{
token = group.Split( ' - ' );
fieldsSelected.Add( int .Parse(token[ 0 ]));
fieldsSelectedDic.Add( int .Parse(token[ 0 ]), token[ 1 ]);
}
}
/// <summary>
/// 获取分页之后的数据
/// </summary>
private void GetStudentTable( int pageSize, int pageIndex)
{
_studentTable = null ;
switch (queryStringWhere)
{
case " jx " :
_studentTable = Helper.StudentPagingResult(
" zpadress,xmqz,xmqy,xmjz,xmjy,jx,zw,gj,sjyqk,zj,csrq,rwrq,xzz,dhd,dhx,fcjp,xh " ,
" tx_xyzl " ,
string .Format( " dwbh='{0}' and jx='{1}' " , classCode, studentType),
" id " ,
pageSize,
pageIndex);
// this.gvStudent.DataBind();
break ;
case " gj " :
_studentTable = Helper.StudentPagingResult(
" zpadress,xmqz,xmqy,xmjz,xmjy,jx,zw,gj,sjyqk,zj,csrq,rwrq,xzz,dhd,dhx,fcjp,xh " ,
" tx_xyzl " ,
string .Format( " dwbh='{0}' and gj='{1}' " , classCode, studentType),
" id " ,
pageSize,
pageIndex);
// this.gvStudent.DataBind();
break ;
case " allyear " :
_studentTable = Helper.StudentPagingResult(
" s.zpadress,s.xmqz,s.xmqy,s.xmjz,s.xmjy,s.jx,s.zw,s.gj,s.sjyqk,s.zj,s.csrq,s.rwrq,s.xzz,s.dhd,s.dhx,s.fcjp,s.xh " ,
" tx_xyzl as s inner join tx_dwsz as dw on s.dwbh=dw.bh " ,
string .Format( @" s.dwbh='{0}' and (dw.kxsj>=convert(datetime,'{1}'+'-01-01',120) and
dw.kxsj<=convert(datetime,'{1}'+'-12-31',120) or dw.bysj>=convert(datetime,'{1}'+'-01-01',120) and
dw.bysj<=convert(datetime,'{1}'+'-12-31',120)) " , classCode, studentType),
" s.id " ,
pageSize,
pageIndex);
// this.gvStudent.DataBind();
break ;
case " new " :
_studentTable = Helper.StudentPagingResult(
" s.zpadress,s.xmqz,s.xmqy,s.xmjz,s.xmjy,s.jx,s.zw,s.gj,s.sjyqk,s.zj,s.csrq,s.rwrq,s.xzz,s.dhd,s.dhx,s.fcjp,s.xh " ,
" tx_xyzl as s inner join tx_dwsz as dw on s.dwbh=dw.bh " ,
string .Format( @" s.dwbh='{0}' and (dw.kxsj>=convert(datetime,'{1}'+'-01-01',120) and
dw.kxsj<=convert(datetime,'{1}'+'-12-31',120)) " , classCode, studentType),
" s.id " ,
pageSize,
pageIndex);
// this.gvStudent.DataBind();
break ;
default :
_studentTable = Helper.StudentPagingResult(
" zpadress,xmqz,xmqy,xmjz,xmjy,jx,zw,gj,sjyqk,zj,csrq,rwrq,xzz,dhd,dhx,fcjp,xh " ,
" tx_xyzl " ,
string .Format( " dwbh='{0}' " , classCode),
" id " ,
pageSize,
pageIndex);
// this.gvStudent.DataBind();
break ;
}
}
#endregion
public void ProcessRequest(HttpContext context)
{
SPSecurity.RunWithElevatedPrivileges( delegate ()
{
GetRequestQueryString();
GetStudentTable( this .pageSize, this .pageIndex);
StudentDetailsTable_Word_V2 customWord = new StudentDetailsTable_Word_V2();
customWord.CreateWordFile();
customWord.SetPageMargin();
customWord.InsertTitle(customWord.ODoc, fileName);
int tableTitleRows = 1 ;
int tableRows = _studentTable.Rows.Count + tableTitleRows;
int tableCols = gvColCount;
customWord.InsertTableToWord(customWord.ODoc, tableRows, fieldsSelected.Count);
Word.Table table = customWord.ODoc.Tables[ 1 ];
customWord.InsertTableTitle(customWord.ODoc, table, fieldsSelected, fieldsSelectedDic);
table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
object row = table.Rows[ 1 ];
customWord.InsertDataToWord(table, _studentTable, tableRows - tableTitleRows, tableCols, fieldsSelected);
#region
string tempFileFullName = customWord.Save(Settings.ImageLocalhostTempSaveDirectory, fileName);
string tempFileName = tempFileFullName.Substring(tempFileFullName.LastIndexOf( " \\ " ) + 1 );
using (FileStream stream = new FileStream(tempFileFullName, FileMode.Open))
{
byte [] fileBytes = new byte [stream.Length];
stream.Read(fileBytes, 0 , ( int )stream.Length);
HttpContext.Current.Response.ContentType = " application/msword " ;
HttpContext.Current.Response.AddHeader( " content-disposition " , " attachment; filename= " + HttpUtility.UrlEncode(tempFileFullName));
HttpContext.Current.Response.OutputStream.Write(fileBytes, 0 , ( int )stream.Length);
} File.Delete(tempFileFullName);
#endregion
});
}
public bool IsReusable
{
get
{
return false ;
}
}
}
}