惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
WordPress大学
WordPress大学
罗磊的独立博客
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
H
Help Net Security
S
SegmentFault 最新的问题
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
D
DataBreaches.Net
雷峰网
雷峰网
GbyAI
GbyAI
宝玉的分享
宝玉的分享

博客园 - yiyanxiyin

一个linq左连接查询速度问题 利用vba实现excel表格连接打印编号(一页两个编号),编号支持前缀 使用反射让linq实现动态查询, 类似拼接sql语句的where 条件 中断工作流并持久化到数据库中【源码】 在非asp.net程序中使用缓存 固定table的行列 固定table的cell宽度,多余的文字隐藏 - yiyanxiyin - 博客园 wcf中异步与双向通讯的区别 解决msmq私有队列不能持久保存的问题 sqlserver中使用查询分析器的一点小技巧 原创:一个相当有用的宏(for vs.net),该宏能大大的提高开发速度 Response.Redirect()与Server.Transfer()的区别 cellIndex在隐藏td中的问题,bug?(ie6) - yiyanxiyin - 博客园 一个format格式问题 - yiyanxiyin - 博客园 参透js 搞不懂的js 个人作品:全文搜索Access中的数据(附.net源代码) 个人作品:存储过程代码生成器(for MS SQL Server) 原创技术文章:保存帐号信息通用类(使用Session或者Cookie)
按模板生成word报表,可扩展,demo可生成多页
yiyanxiyin · 2012-02-28 · via 博客园 - yiyanxiyin

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Data.SqlClient;
using System.Web;
using System.Data;

namespace MyPublicClass
{
    /// <summary>
    
/// 报表名称,和模板名称一致, 该枚举可无限扩展
    
/// </summary>
    public enum WordTemplateType
    {
        管道吹扫清洗检验记录,
    }
    /// <summary>
    
/// 生成word报表
    
/// yiyanxiyin@qq.com
    
/// 2012-2-28
    
/// </summary>
    public class WordReport
    {
        /// <summary>
        
/// 生成word报表文件
        
/// </summary>
        
/// <param name="wordTemplate">word模板</param>
        
/// <param name="parameter">参数, 自定任意参数</param>
        
/// <returns>生成的文件名</returns>
        public static string ExportDataToWord(WordTemplateType wordTemplate, object[] parameter)
        {
            Microsoft.Office.Interop.Word.Document wDoc = null;
            Microsoft.Office.Interop.Word.Application wApp = null;

            string filePath = "", appPath;
            filePath = System.Web.HttpContext.Current.Server.MapPath("~/ExcelTemplate/" + wordTemplate.ToString() + ".doc");
            OpenWordDoc(filePath, ref wDoc,ref wApp);
            try
            {
                //扩展该switch定制报表
                switch (wordTemplate)
                {
                    case WordTemplateType.管道吹扫清洗检验记录:
                        Export_ClearAndCheckRecord(wApp,wDoc, parameter);
                        
                        break;
                }

                filePath = filePath.Substring(0, filePath.Length - 4);
                filePath = filePath.Replace("ExcelTemplate""ExcelFiles");

                filePath = getFileName(filePath, out appPath);
                wDoc.SaveAs(filePath);
            }
            finally
            {
                if (wDoc != null)
                {
                    wDoc.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
                    wDoc = null;
                }
                if (wApp != null)
                {
                    wApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
                    wApp = null;
                }
                GC.Collect();
            }
            return appPath;
        }
        private static void OpenWordDoc(string FileName, ref Microsoft.Office.Interop.Word.Document wDoc, ref  Microsoft.Office.Interop.Word.Application WApp)
        {
            if (FileName == ""return;
            Microsoft.Office.Interop.Word.Document thisDocument = null;
            Microsoft.Office.Interop.Word.FormFields formFields = null;
            Microsoft.Office.Interop.Word.Application thisApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            thisApplication.Visible = true;
            thisApplication.Caption = "";
            thisApplication.Options.CheckSpellingAsYouType = false;
            thisApplication.Options.CheckGrammarAsYouType = false;

            Object filename = FileName;
            Object ConfirmConversions = false;
            Object ReadOnly = true;
            Object AddToRecentFiles = false;

            Object PasswordDocument = System.Type.Missing;
            Object PasswordTemplate = System.Type.Missing;
            Object Revert = System.Type.Missing;
            Object WritePasswordDocument = System.Type.Missing;
            Object WritePasswordTemplate = System.Type.Missing;
            Object Format = System.Type.Missing;
            Object Encoding = System.Type.Missing;
            Object Visible = System.Type.Missing;
            Object OpenAndRepair = System.Type.Missing;
            Object DocumentDirection = System.Type.Missing;
            Object NoEncodingDialog = System.Type.Missing;
            Object XMLTransform = System.Type.Missing;

            Microsoft.Office.Interop.Word.Document wordDoc =
             thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
             ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
             ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
             ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
             ref NoEncodingDialog, ref XMLTransform);

            thisDocument = wordDoc;
            wDoc = wordDoc;
            WApp = thisApplication;
            formFields = wordDoc.FormFields;

        }

        private static string getFileName(string fileName, out string appFilePath)
        {
            System.DateTime currentTime = System.DateTime.Now;
            Random rd = new Random();
            string TempFileName = fileName + currentTime.ToString("yyyyMMddHHmm") + rd.Next().ToString() + ".doc";
            string CurrentPath = System.Web.HttpContext.Current.Server.MapPath("~/ExcelFiles/");
            string CurrentMonth = currentTime.ToString("yyyyMM");
            if (!System.IO.Directory.Exists(CurrentPath + "\\" + CurrentMonth))
            {
                System.IO.Directory.CreateDirectory(CurrentPath + "\\" + CurrentMonth);
            }
            System.IO.FileInfo fi = new System.IO.FileInfo(TempFileName);
            appFilePath = (HttpContext.Current.Request.ApplicationPath.EndsWith("/") ? HttpContext.Current.Request.ApplicationPath : HttpContext.Current.Request.ApplicationPath + "/") + "ExcelFiles/" + CurrentMonth + "/" + fi.Name;
            appFilePath.Replace("//""/");
            return CurrentPath + CurrentMonth + "\\" + fi.Name;
        }

        /// <summary>
        
/// 管道吹扫清洗检验记录(可生成多页,每页12行)
        
/// </summary>
        
/// <param name="wSheet"></param>
        
/// <param name="wSheet"></param>
        
/// <param name="parameter">参数, 自定任意参数,在此函数中解析</param>
        private static void Export_ClearAndCheckRecord(Application wApp, Document wDoc, object[] parameter)
        {
            string projectName = parameter[0].ToString();
            string cellProject = parameter[1].ToString();
            string packetNumber = parameter[2].ToString();

            System.Data.DataTable detailDataTable = (System.Data.DataTable)parameter[3];

            wDoc.Bookmarks["ProjectName"].Range.Text = projectName;
            wDoc.Bookmarks["CellProject"].Range.Text = cellProject;
            wDoc.Bookmarks["PacketNumber"].Range.Text = packetNumber;

            if (detailDataTable.Rows.Count == 0return;

            //计算需要几个表格(每个表格显示12条数据)
            int tablecount = detailDataTable.Rows.Count / 12 + (detailDataTable.Rows.Count % 12 == 0 ? 0 : 1);
            //生成足够多的空表格
            while (tablecount > 1)
            {
                wDoc.Tables[1].Select();
                wApp.Selection.Copy();
                object mymissing = System.Reflection.Missing.Value;
                object myunit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                wApp.Selection.EndKey(ref myunit, ref mymissing);
                object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
                wApp.Selection.InsertBreak(ref pBreak);
                wApp.Selection.Paste();

                tablecount--;
            }

            int i = 0;

            foreach (DataRow dr in detailDataTable.Rows)
            {
                wDoc.Tables[i / 12 + 1].Cell(i % 12 + 91).Range.Text = dr["pipelinecode"].ToString();
                wDoc.Tables[i / 12 + 1].Cell(i % 12 + 92).Range.Text = dr["material"].ToString();

                i++;
            }
        }
        //在此参考以上方法扩展自定报表

    }
}

System.Data.DataSet ds = SqlData.Table_WeldTestPressure.ClearAndCheckRecordReport(projectId, singleProject, unitProject,cellProject, packetNumber);
string wordfile= WordReport.ExportDataToWord(WordTemplateType. 管道吹扫清洗检验记 录, new object[] { SqlData.Table_ProjectTable.GetProjectName(projectId), cellProject, packetNumber, ds.Tables[0] });

生成结果: