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

简介: 一、word这是我以前工作时写过的一个业务逻辑处理类,里面有不少文件操作的方法,这里主要关注一下C#对word的操作。

一、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文档


目录
相关文章
|
4月前
|
小程序
公众号如何添加附传Word、Excel、Pdf、PPT文档
公众号里添加一些文档给公众号粉丝下载,比如课件PPT、申请表Word文档、岗位需求Excel表、大赛入围/获奖名单等。公众号本身是不支持直接上传文件的,但我们可以通过附件小程序“间接”上传文件。
735 0
|
8月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
464 10
|
8月前
|
存储 监控 算法
基于 C# 的局域网计算机监控系统文件变更实时监测算法设计与实现研究
本文介绍了一种基于C#语言的局域网文件变更监控算法,通过事件驱动与批处理机制结合,实现高效、低负载的文件系统实时监控。核心内容涵盖监控机制选择(如事件触发机制)、数据结构设计(如监控文件列表、事件队列)及批处理优化策略。文章详细解析了C#实现的核心代码,并提出性能优化与可靠性保障措施,包括批量处理、事件过滤和异步处理等技术。最后,探讨了该算法在企业数据安全监控、文件同步备份等场景的应用潜力,以及未来向智能化扩展的方向,如文件内容分析、智能告警机制和分布式监控架构。
226 3
|
11月前
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
1701 5
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
244 9
|
9月前
|
存储 JSON API
如何将 Swagger 文档导出为 PDF 文件
你会发现自己可能需要将 Swagger 文档导出为 PDF 或文件,以便于共享和存档。在这篇博文中,我们将指导你完成将 Swagger 文档导出为 PDF 格式的过程。
|
6月前
|
C#
【PDF提取内容改名】批量提取PDF指定区域内容重命名PDF文件,PDF自动提取内容命名的方案和详细步骤
本工具可批量提取PDF中的合同编号、日期、发票号等关键信息,支持PDF自定义区域提取并自动重命名文件,适用于合同管理、发票处理、文档归档和数据录入场景。基于iTextSharp库实现,提供完整代码示例与百度、腾讯网盘下载链接,助力高效处理PDF文档。
843 40
|
6月前
|
编译器 Python
如何利用Python批量重命名PDF文件
本文介绍了如何使用Python提取PDF内容并用于文件重命名。通过安装Python环境、PyCharm编译器及Jupyter Notebook,结合tabula库实现PDF数据读取与处理,并提供代码示例与参考文献。
|
7月前
|
数据采集 存储 API
Python爬虫结合API接口批量获取PDF文件
Python爬虫结合API接口批量获取PDF文件

热门文章

最新文章