C#计算word,pdf,Excle文档的页数

本文介绍如何使用C#计算Word、PDF及Excel文档的页数。针对Word文档,通过Microsoft.Office.Interop.Word实现;PDF文档则利用Spire.Pdf完成;而Excel文档则先转换为PDF格式再计算页数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#计算word,pdf,Excle文档的页数

一:计算word的页数:

using Microsoft.Office.Interop.Word;//需要导入的命名空间,需要从NuGet程序包里下载
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalculatePageFactory
{
    public class CalculateWordPage
    {

 private static Microsoft.Office.Interop.Word.ApplicationClass myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
        static object oMissing = System.Reflection.Missing.Value;
        /// <summary>
        /// 得到Word文件的页数
        /// </summary>
        /// <param name="path">word文件的路径</param>
        /// <returns></returns>
        public static int GetWordPageCount(string path)
        {
            try
            {
                myWordApp.Visible = false;
                object filePath = path; //这里是Word文件的路径
                //打开文件
                Microsoft.Office.Interop.Word.Document myWordDoc = myWordApp.Documents.Open(
                    ref filePath, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                //下面是取得打开文件的页数
                int pages = myWordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref oMissing);
                myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                return pages;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}

注意:Microsoft.Office.Interop.Word.ApplicationClass当创建这个对象时,可能会报错。原因是没有你引入的using Microsoft.Office.Interop.Word引用里没有修改它的属性,右击引用里的Microsoft.Office.Interop.Word点击属性,找到嵌入互操作类型把true改为false,就Ojbk了。下面上图:

 

二:计算pdf的页数:

using Spire.Pdf;//引入命名空间,没有的话去NuGet包里下载
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalculatePageFactory
{
   public class CalculatePDFPage
    {
        /// <summary>
        /// 得到PDF文件的页数
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static int GetPDFPageCount(string filePath)
        {
            PdfDocument pdf = new PdfDocument();

            //加载PDF文档
            pdf.LoadFromFile(filePath);

            //获取PDF页数
            int page = pdf.Pages.Count;
            return page;
        }
    }
}

三:计算Exlce文件的页数

思路:Excle直接计算页数的话是很麻烦的,我查了好多资料都没有找到,所以我换了一种思路,就是把Excle先转换为PDF格式的文件,之后再计算转换后的页数(不用担心页数会变,转换后的页数和之前的Excle的文件页数是一样的)

具体步骤:

1.先把Excle进行转换PDF格式的文档

using Microsoft.Office.Interop.Excel;//引入的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SwitchType
{
   public class SwitchPDFType
    {
        //Microsoft.Office.Interop.Word.WdExportFormat wd = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
        //Microsoft.Office.Interop.Excel.XlFixedFormatType excelType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
        /// <summary>
        /// 将excel文档转换成PDF格式
        /// </summary>
        /// <param name="sourcePath">需要转换的文件路径</param>
        /// <param name="targetPath">转换好的之后 需要保存的文件路径</param>
        /// <param name="targetType">这是个枚举类型</param>
        /// <returns></returns>
        public bool Convert(string sourcePath, string targetPath, XlFixedFormatType targetType)
        {
            bool result;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.Application application = null;
            Workbook workBook = null;
            try
            {
                application = new Microsoft.Office.Interop.Excel.Application();
                object target = targetPath;
                object type = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);

                workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}
2.再将转换好的pdf文件计算器页数就行

   public class CalatewitchPage
    {
        /// <summary>
        /// 处理转换为PDF的文件
        /// </summary>
        /// <param name="filePath">上传的Excle的文件路径</param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetSwitchedPDF(string filePath, string[] type)
        {
            SwitchPDFType switchPDF = new SwitchPDFType();
            int excle = 0;
            string newFileName = null;
            StringBuilder sb = new StringBuilder();
        Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = (Microsoft.Office.Interop.Excel.XlFixedFormatType)excle;
            bool result = switchPDF.Convert(filePath, filePath, targetType);//调用Excle的方法
            //如果转换成功
            if (result)
            {
                string[] newType = new string[type.Length + 1];
                for (int i = 0; i < newType.Length - 1; i++)
                {
                    newType[i] = type[i] + ".";
                }
                newType[newType.Length - 1] = "pdf";
                for (int i = 0; i < newType.Length; i++)
                {
                    sb.Append(newType[i]);
                }
            }
            newFileName = sb.ToString();
            return newFileName;//得到转换后的文件名 
        }
    }

//3.得到转换后的文件路径

 string newFileName = CalatewitchPage.GetSwitchedPDF(filePath, type);
  filePath = HttpContext.Current.Server.MapPath("~/file/" + newFileName);//转换后的文件路径

//4.调用计算pdf的页数就行了,代码就不写了,文章最上面有pdf页数的计算方法,直接把路径传过去就行了

如果有哪位大神能直接不用转换直接计算Excle页数的,请赐教!

### 配置 `el-upload` 组件以限制上传文件类型 为了确保仅允许特定类型的文件被上传,可以利用 `accept` 属性来限定文件扩展名。对于 Word 文档 (.doc 和 .docx),PDF 文件 (.pdf) 及 Excel 表格 (xls 和 xlsx),相应的 MIME 类型或文件扩展名应当如下所示: - Microsoft Word: `.doc`, `.docx` - Adobe PDF: `.pdf` - Microsoft Excel: `.xls`, `.xlsx` 通过设置 `accept` 参数为这些文件类型的组合字符串,能够有效地过滤掉不符合条件的文件。 ```html <template> <div> <!-- 使用 accept 来控制可接受的文件类型 --> <el-upload :auto-upload="false" http-request="handleUploadFile" :on-change="handleChange" :before-upload="beforeAvatarUpload"> <el-button type="primary">点击上传</el-button> </el-upload> </div> </template> <script> export default { methods: { beforeAvatarUpload(file) { const validTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; let isValidType = false; for(let i=0; i<validTypes.length;i++){ if(validTypes[i].toLowerCase() === file.type.toLowerCase()){ isValidType=true; break; } } if (!isValidType) { this.$message.error('只能上传WordPDF 或者 Excel 文件!'); } return isValidType; }, handleChange(file, fileList){ console.log("file changed", file); }, handleUploadFile(params){ // 自定义上传逻辑处理函数 console.log("custom upload function called with params:",params.file); } } } </script> ``` 上述代码片段展示了如何配置 `el-upload` 组件以便只接收指定格式的文件,并阻止其他类型的文件上传[^1]。此外,在实际应用中可能还需要考虑用户体验方面的问题,比如当用户尝试上传不支持的文件时给出提示信息等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值