C#对word、excel、pdf等格式文件的操作总结

一、word

这是我以前工作时写过的一个业务逻辑处理类,里面有不少文件操作的方法,这里主要关注一下C#对word的操作。里面的方法可以直接拿出来用,主要是通过word的dot模版来进行创建word、替换word等操作。

namespace Excel2Word
{
    public class BLL
    {
        private Microsoft.Office.Interop.Word.Application app = null;//全局变量 word应用程序

        /// <summary>
        /// 从Excel中读取数据
        /// </summary>
        /// <param name="excelPath"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static DataSet GetDataFromExcel(string excelPath, string sheetName)
        {
            DataSet ds = new DataSet();
            string strConn = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + excelPath.ToString().Trim() + "; Extended Properties=Excel 8.0;";

            try
            {
                using (OleDbConnection conn = new OleDbConnection(strConn))
                {
                    conn.Open();

                    OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
                    oda.Fill(ds);
                }
            }
            catch
            {
                throw new Exception("获取Excel数据时发生异常...");
            }
            return ds;
        }
      
        /// <summary>
        /// Word文本替换
        /// </summary>
        /// <param name="doc">文档</param>
        /// <param name="args">要替换的内容</param>
        public void ReplaceWord(Document doc, Dictionary<string, string> args)
        {
            try
            {
                object first = 0;
                object last = doc.Characters.Count;
                Range range = doc.Range(ref first, ref last);

                Microsoft.Office.Interop.Word.Find finder = range.Find;
                finder.ClearFormatting();

                object missingValue = Type.Missing;
                object replaceArea = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                foreach (var item in args)
                {
                    object findStr = "{" + item.Key.Trim() + "}";
                    object replaceStr = item.Value.Trim();

                    //替换内容
                    finder.Execute(ref findStr, ref missingValue, ref missingValue,
                      ref missingValue, ref missingValue, ref missingValue,
                      ref missingValue, ref missingValue, ref missingValue,
                      ref replaceStr, ref replaceArea, ref missingValue,
                      ref missingValue, ref missingValue, ref missingValue);
                }
            }
            catch
            {
                return;
            }
        }


        /// <summary>
        /// word文档资源释放
        /// </summary>
        /// <param name="doc">要释放资源的文档</param>
        public void DisposeWord(Document doc)
        {
            try
            {
                object oMissing = System.Reflection.Missing.Value;

                if (doc != null)
                {
                    //关闭Word并回收资源
                    doc.Close(ref oMissing, ref oMissing, ref oMissing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                    doc = null;
                }

                if (app != null)
                {
                    app.Quit(ref oMissing, ref oMissing, ref oMissing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    app = null;
                    GC.Collect();
                }
            }
            catch
            {
                return;
            }
        }

        /// <summary>
        /// 从模板创建Word文件
        /// </summary>
        /// <param name="fileName">模板位置及名称</param>
        /// <returns></returns>
        public Document CreateWord(string fileName, string dsr)
        {
            try
            {
                app = new Microsoft.Office.Interop.Word.Application();//打开word程序
                Document doc = new Document();//创建word对象
                object unknow = Type.Missing;
                string date = DateTime.Now.ToShortDateString();
                object savefilename = @"D:\" + dsr + ".doc";//保存路径
                object File = fileName;
                app.Visible = false;//设置word程序为不可见
                doc = app.Documents.Open(ref File,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//打开word文档

                doc.SaveAs(ref savefilename, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//保存word文档

                return doc;
            }
            catch
            {
                return null;
            }
        }
    }
}

二、excel

webform中,导出excel的代码:

        public void ExportResult(DataTable dt, string excelName)
        {
            Response.Clear();
            Response.Charset = "";
            Response.ContentType = "applicationnd.ms-xls";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(sw);

            DataGrid dg = new DataGrid();
            dg.DataSource = dt;
            dg.DataBind();
            dg.RenderControl(htmlWrite);
            Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(excelName));
            Response.Write(sw.ToString());
            Response.End();
        }

如果遇到身份证等类型的字段,由于科学计数法的原因导出excel之后很可能会“截断”,因此有必要对这种长整型的字段进行处理。

        /// <summary>
        /// 过滤低位非打印字符
        /// </summary>
        /// <param name="tmp"></param>
        /// <returns></returns>
        private string ReplaceLowOrderASCIICharacters(string tmp)
        {
            StringBuilder info = new StringBuilder();
            foreach (char cc in tmp)
            {
                int ss = (int)cc;
                if (((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32)))
                    info.AppendFormat(" ", ss);
                else info.Append(cc);
            }
            return info.ToString();
        }

winform中,客户端生成excel的代码:

前提是要安装office,原理是通过office进程生成excel文件。

        /// <summary>
        /// 从DataSet生成Excel
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <param name="strExcelFileName">文件名</param>
        public void ExportExcelByDataSet(DataSet ds, string strExcelFileName)
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            int rowIndex = 1;
            int colIndex = 0;

            excel.Application.Workbooks.Add(true);

            DataTable dt = ds.Tables[0];
            foreach (DataColumn col in dt.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }

            foreach (DataRow row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;

                foreach (DataColumn col in dt.Columns)
                {
                    colIndex++;
                    excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                }
            }

            excel.Visible = false;
            excel.ActiveWorkbook.SaveAs(strExcelFileName + ".XLS", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);

            excel.Quit();
            excel = null;
            GC.Collect();
        }

三、pdf

搜索《PDF文件制作全攻略》,可以找到现成的资料,里面的代码和文档也相对比较齐全、清晰,这里简单做个示例demo——生成一个带章节的,内容为图片的pdf文档。

实现步骤:

1)在vs环境下新建项目,引用 ICSharpCode.SharpZipLib.dll、itextsharp.dll 这两个dll文件

2)在按钮事件下输入如下代码:

            //设置版面为A4大小
            Document document = new Document(PageSize.A4);

            //创建一个test.pdf文件
            PdfWriter.getInstance(document, new FileStream("test.pdf", FileMode.Create));

            document.Open();//打开pdf文档

            try
            {
                string[] images = Directory.GetFiles("test/");

                for (int i = 0; i < images.Length; i++)
                {
                    //定义章节
                    Chapter chapter = new Chapter(new Paragraph(images[i]), i + 1);

                    //加入章节
                    document.Add(chapter);

                    //获得图片
                    iTextSharp.text.Image tempImage = iTextSharp.text.Image.getInstance(images[i]);

                    //设置图片大小为原图的70%
                    tempImage.scalePercent(70);

                    //文档加入图片
                    document.Add(tempImage);

                    //文档新建一页
                    document.newPage();
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
            document.Close();//关闭pdf文档


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 C# 的 Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 库,将 WordExcel 文件转换为 PDF 格式,然后使用第三方的 PDF 打印工具批量打印这些 PDF 文件。以下是具体步骤: 1. 引用 Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 库,如果您使用的是 Visual Studio,可以在“解决方案资源管理器”中右键单击项目名称,选择“添加”->“引用”->“COM”选项卡,然后勾选“Microsoft Word xx.x Object Library”和“Microsoft Excel xx.x Object Library”; 2. 创建 WordExcel 应用程序对象,打开需要转换的 WordExcel 文件; 3. 使用应用程序对象的“ExportAsFixedFormat”方法将 WordExcel 文件转换为 PDF 格式; 4. 关闭 WordExcel 文件,销毁应用程序对象; 5. 下载并安装一个第三方的 PDF 打印工具,如 Adobe Acrobat Reader 或 Foxit Reader; 6. 使用 C# 调用第三方的 PDF 打印工具,将需要打印的 PDF 文件添加到打印列表中; 7. 配置打印选项,如打印机、打印质量等; 8. 点击“打印”按钮,即可批量打印 PDF 文件。 需要注意的是,在转换 WordExcel 文件为 PDF 格式时,可能会出现格式错位、字体不一致等问题。建议在转换前进行一次预览,确保转换后的 PDF 文件符合预期。同时,如果您打算开发一个批量打印工具,还需要考虑如何对文件进行批量处理、如何处理转换和打印过程中可能发生的异常等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值