在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
如果开发的ASP.NET应用需要导出数据到word中的话,需要注意一点,就是导出按钮,建议不要使用button或者linkbutton在后代码中直接处理,最好使用ashx一般处理程序,或者是ajax异步处理一下,要不然后台处理的话,每次只能点击一次,不能重复导出,要刷新页面才可以,使用ashx或者ajax就可以保证重复点击导出都没有问题。 使用asp.net开发导出word格式的数据,如果是图片的话,需要先将图片下载到本地,然后从本地添加到word中,要不然你的文档拷贝到不能上网的地方就会出现红叉啊,路径问题。
result;
}
;
还有啊,需要设置服务器的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
控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Word文档 * 这些帐户仅在计算机上安装有 IIS 的情况下才存在。
运行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)
.Close();
}
实用工具类
using System;
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(); } } }
word操作代码,设置word格式
using System; 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 |
请发表评论