c#玩转文档及图像大全【基于客户端wpf】

目录

用到的公共库介绍

1、c#读取xlsx及xls

2、c# 将excel转tif图像

3、c#获取tif、pdf、jpg属性方法

4、c# 将实体数据填充进excel模板

5、c# 将多个tif文件合并成一个

 6、c# 根据tif、png、pdf文件生成对应的数字摘要

 7、c# 将数据写入excel指定位置(指定行和列)

 8、c# 将list生成excel

用到的公共库介绍

可能有遗漏,可以根据vs提示自行从nuget下载

using Excel = Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using Encoder = System.Drawing.Imaging.Encoder;
using System.Security.Cryptography;
using System.Drawing;
using System.Drawing.Imaging;
using OfficeOpenXml;

1、c#读取xlsx及xls

a:读取xlsx文件

  public List<RecordsModel> GetAJFileListData1(string filepath)
        {
            //自己定义实体类
            List<RecordsModel> filedata = new List<RecordsModel>();
            try
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (var package = new ExcelPackage(new FileInfo(filepath)))
                {
                    var worksheet = package.Workbook.Worksheets[1];
                    //获取行数
                    int rowsCount = worksheet.Dimension.Rows;
                    //获取列数
                    int columnsCount = worksheet.Dimension.Columns;
                  
                  //循环行
                    for (int i = 1; i <= rowsCount; i++)
                    {
                      RecordsModel entity = new RecordsModel();
                       
                        for (int j = 1; j <= columnsCount; j++)
                        {
                            switch (j)
                            {
                                case 1:
                                    if (!rowisnull)
                                    {
                                        entity.RowIndex = i;
                                        entity.rowid = worksheet.Cells[i, j].Value?.ToString();
                                    }
                                    break;
 ......
                            }
                        }

                       filedata.Add(entity);
                    }
                }
                return filedata;
            }
            catch (Exception ex)
            {
                Logger.Error("读取异常:" + ex.Message);
                return null;
            }
        }

 b:读取xls文件

 public List<RecordsModel> GetAJFileListData(string filepath)
        {
            List<RecordsModel> filedata = new List<RecordsModel>();
            try
            {
                Application excelApp = new Application();
                Excel.Workbook workbook = excelApp.Workbooks.Open(filepath);
                Excel.Worksheet worksheet = workbook.Sheets[1];
                //
                //获取行数
                int rowsCount = worksheet.UsedRange.Rows.Count;
                //获取列数
                int columnsCount = worksheet.UsedRange.Columns.Count;

              
            
                for (int i = 1; i <= rowsCount; i++)
                {
                    RecordsModel entity = new RecordsModel();
                    
                    for (int j = 1; j <= columnsCount; j++)
                    {
                        switch (j)
                        {
                            case 1:
                                if (!rowisnull)
                                {
                                    entity.RowIndex = i;
                                    entity.rowid = worksheet.Cells[i, j].Value?.ToString();
                                }
                                break;
                                ......
                        }
                    }
                    filedata.Add(entity);
                }
                workbook.Close(false);
                excelApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                worksheet = null;
                workbook = null;
                excelApp = null;
                GC.Collect();
                return filedata;
            }
            catch (Exception ex)
            {
                Logger.Error("异常:" + ex.Message);
                return null;
            }
        }

2、c# 将excel转tif图像

 
 string jnpath ="这里是excel存放的路径";
//这里会有很多收费库,将excel赚tif文件,因为我比较穷,所以用了免费的库进行处理,缺点就是需要先将文件转成pdf,然后再转成tif文件
//这里设置excel转pdf后,文件存放的路径,自行选择即可
  string jnpdfpath = folderPath + "\\xxx.pdf";
//这里设置pdf转tif后,文件存放的路径,自行选择即可
   string jntifpath = folderPath + "\\xxx.tif";
//调用方法
importexcel.EccelToTif(jnpath, jnpdfpath, jntifpath);
//方法实现如下

 /// <summary>
        /// 将excel转成tif图片
        /// </summary>
        public bool EccelToTif(string filepath, string outfilepathpdf, string outfilepath)
        {
            bool result = true;
            try
            {
                //将excel转pdf
                Excel.Application excelApp = new Excel.Application();
                Excel.Workbook workbook = excelApp.Workbooks.Open(filepath);
                workbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, outfilepathpdf);
                workbook.Close(false);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelApp);
                Marshal.ReleaseComObject(workbook);
                Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
                document.LoadFromFile(outfilepathpdf);
                //调用方法SaveAsImage()将PDF文档保存为tiff格式
                JoinTiffImages(SaveAsImage(document), outfilepath, EncoderValue.CompressionLZW);

                //设置其分辨率
                using (var tiff = Tiff.Open(outfilepath, "a"))
                {
                    var pageCount = tiff.NumberOfDirectories();
                    for (int i = 0; i < pageCount; i++)
                    {
                        tiff.SetDirectory((short)i);
                        tiff.SetField(TiffTag.XRESOLUTION, 300);
                        tiff.SetField(TiffTag.YRESOLUTION, 300);
                        tiff.WriteDirectory();
                    }
                }
                //删除pdf文件
                DeletePdfFile(outfilepathpdf);
                //释放资源
                if (document != null)
                {
                    document.Close();
                    document.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger.Error("excel转tif文件失败,文件路径:" + filepath + ",错误详情:" + ex.Message);
                result = false;
            }
            return result;
        }

  //自定义方法SaveAsImage()将PDF文档保存图像文件
        private static Image[] SaveAsImage(Spire.Pdf.PdfDocument document)
        {
            Image[] images = new Image[document.Pages.Count];
            for (int i = 0; i < document.Pages.Count; i++)
            {
                images[i] = document.SaveAsImage(i);
            }
            return images;
        }

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
            for (int j = 0; j < encoders.Length; j++)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
        }

//自定义JoinTiffImages()方法,使用指定编码器和图像编码器参数将图像从pdf页面保存到tiff图像类型,。
        public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
        {
            Encoder enc = Encoder.SaveFlag;
            EncoderParameters ep = new EncoderParameters(2);
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);
            Image pages = images[0];
            int frame = 0;
            ImageCodecInfo info = GetEncoderInfo("image/tiff");
            foreach (Image img in images)
            {
                if (frame == 0)
                {
                    pages = img;
                    pages.Save(outFile, info, ep);
                }
                else
                {
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
                    pages.SaveAdd(img, ep);
                }
                if (frame == images.Length - 1)
                {
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
        }
 public void DeletePdfFile(string pdfFilePath)
        {
            if (File.Exists(pdfFilePath))
            {
                File.Delete(pdfFilePath);
            }
        }

3、c#获取tif、pdf、jpg属性方法
 

     switch (suffix)
                        {
                            case ".tif":
                                using (Tiff image = Tiff.Open(filepath, "r"))
                                {
                                    if (image != null)
                                    {
                                        var xxx = image.GetField(TiffTag.XRESOLUTION);
                                        // 读取TIFF图像文件的X分辨率和Y分辨率
                                        float xResolution = image.GetField(TiffTag.XRESOLUTION)[0].ToFloat();
                                        float yResolution = image.GetField(TiffTag.YRESOLUTION)[0].ToFloat();
                                        
                                    }
                                }
                                
                                break;

                            case ".pdf":
                                //获取pdf页数,这里介绍两种方法
                                //第一种
                                using (PdfReader reader = new PdfReader(filepath))
                                    {
                                        imagecount += reader.NumberOfPages;
                                    }
                                    //第二种
                                 //using (PdfDocument pdfDocument =             PdfSharp.Pdf.IO.PdfReader.Open(filepath, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import))
                                //{
                                //    imagecount += pdfDocument.PageCount; // 获取PDF文档的页数
                                //}
                        
                                break;

                            case ".jpg":
                             //获取照片宽高以及分辨率
                                Bitmap bmp = new Bitmap(filepath);
                                int width = bmp.Width;
                                int height = bmp.Height;
                                int bitDepth = System.Drawing.Image.GetPixelFormatSize(bmp.PixelFormat);
                                float dpiX = bmp.HorizontalResolution;
                                float dpiY = bmp.VerticalResolution;
                                
                                break;
                          
                        }

4、c# 将实体数据填充进excel模板

 public void SetDataInputCover(string param1, string param2, string param3, string outputPath, string templatePath)
        {
//填充数据后,excel保存的位置
            string exceloutpath = outputPath + "\\0.xls";
            
            // 创建Excel应用程序对象
            Excel.Application excelApp = new Excel.Application();
            excelApp.Visible = false;

            // 打开模板文件--templatePath为模板路径
            Excel.Workbook workbook = excelApp.Workbooks.Open(templatePath);

            // 获取工作表对象
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1];

            // 将数据导入到工作表中
            if (param1.Length <= 25)
            {
//设置行列即可
                worksheet.Cells[10, 2] = param1;//标题
            }
            else
            {
                worksheet.Cells[10, 2] = param1.Substring(0, 25);//标题
                worksheet.Cells[12, 2] = param1.Substring(25, param1.Length - 25);//标题
            }
            //worksheet.Cells[17, 3] = param2;
            worksheet.Cells[18, 3] = param3;

            // 保存并关闭Excel文件
            workbook.SaveAs(exceloutpath);
            workbook.Close();
            // 关闭Excel应用程序
            excelApp.Quit();
        }

5、c# 将多个tif文件合并成一个

  List<string> delmergejnlist = new List<string>();
  //需要合并的路径
  mergejnlist.Add("D:\\0.tif");
  mergejnlist.Add("D:\\1.tif");
  mergejnlist.Add("D:\\2.tif");
//这个是合并后的tif文件保存路径
 string zeropath =  "D:\\新文件.tif";

//然后调用方法

  public static bool MergeTif_(string outputfile, List<string> files)
        {
            bool result = true;
            Encoder encoder = Encoder.SaveFlag;
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
            ImageCodecInfo codecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(enc => enc.FormatID == ImageFormat.Tiff.Guid);
            Image outputImage = null;
            try
            {
                    foreach (var file in files)
                    {
                        using (Image inputImage = Image.FromFile(file))
                        {
                            int pageCount = inputImage.GetFrameCount(FrameDimension.Page);
                            for (int i = 0; i < pageCount; i++)
                            {
                                inputImage.SelectActiveFrame(FrameDimension.Page, i);
                                if (outputImage == null)
                                {
                                    outputImage = inputImage.Clone() as Image;
                                    outputImage.Save(outputfile, codecInfo, encoderParams);
                                }
                                else
                                {
                                    EncoderParameters encoderParams1 = new EncoderParameters(1);
                                    encoderParams1.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
                                    outputImage.SaveAdd(inputImage, encoderParams1);
                                }
                            }
                        }
                    }
                    if (outputImage != null)
                    {
                        EncoderParameters encoderParams2 = new EncoderParameters(1);
                        encoderParams2.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
                        outputImage.SaveAdd(encoderParams2);
                    } 
            }
            catch (Exception ex)
            {
                Logger.Error("合并tif失败,详情:" + ex.Message);
                result = false;
            }
            finally
            {
                outputImage?.Dispose();
            }
            return result;
        }

 6、c# 根据tif、png、pdf文件生成对应的数字摘要



  //参数1:文件地址,参数2,生成的数字摘要,
public bool CreateDigitalAbstract(string filePath, out string DigitalAbstract)
        {
            bool result = true;
            DigitalAbstract = "";
            try
            {
                byte[] fileData = File.ReadAllBytes(filePath); // 读取文件数据
                byte[] hashBytes = null;
                using (SHA256 sha256 = SHA256.Create())
                {
                    hashBytes = sha256.ComputeHash(fileData); // 计算哈希值
                }
                DigitalAbstract = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); // 将字节数组转换为字符串--将字符串转小写
            }
            catch (Exception ex)
            {
                Logger.Error("生成数字摘要失败!详情:" + ex.Message);
                result = false;
            }
            return result;
        }

 7、c# 将数据写入excel指定位置(指定行和列)

 /// <summary>
        ///  
        /// </summary>
        /// <param name="excelFilePath">文件路径</param>
        /// <param name="sheetIndex">excel表编号</param>
        /// <param name="row">指定行</param>
        /// <param name="column">指定列</param>
        /// <param name="text">需要插入的文本</param>
 /// <param name="fontname ">字体名称</param>
 /// <param name="fontsize">字体大小</param>
        public void WriteTextToExcel(string excelFilePath, int sheetIndex, int row, int column, string text, string fontname = "", int fontsize = 0)
        {
            bool isright = true;
            if (string.IsNullOrEmpty(fontname))
            {
                isright = false;
                fontname = "宋体";
            }
            if (fontsize == 0)
            {
                fontsize = 12;
            }
            var app = new Application();
            var workbook = app.Workbooks.Open(excelFilePath);
            var worksheet = (Excel.Worksheet)workbook.Sheets[sheetIndex];
            var range = worksheet.Cells[row, column] as Excel.Range;
            if (range != null)
            {
                range.Value2 = text;
                if (isright)
                {
                    range.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                }
                else
                {
                    range.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                }
                range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
                range.Font.Name = fontname;
                range.Font.Size = fontsize;
                Marshal.ReleaseComObject(range);
            }
            //workbook.Save();
            app.DisplayAlerts = false;
            workbook.SaveAs(excelFilePath, ConflictResolution: Excel.XlSaveConflictResolution.xlLocalSessionChanges);
            app.DisplayAlerts = true;

            workbook.Close();
            app.Quit();
            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(app);
        }

 8、c# 将list生成excel

importexcel.ExportToExcel(Reportlist, "D:\\报告.xlsx")
//方法实现:
  public bool ExportToExcel<T>(List<T> list, string path)
        {
            var result = true;
            try
            {
                // 创建Excel对象
                Application excel = new Application();
                Excel.Workbook workbook = excel.Workbooks.Add(Missing.Value);
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
                // 设置表头
                PropertyInfo[] properties = typeof(T).GetProperties();
                //for (int i = 0; i < properties.Length; i++)
                //{
                //    worksheet.Cells[1, i + 1] = properties[i].Name;
                //}
                worksheet.Cells[1, 1] = "顺序号";
                worksheet.Cells[1, 2] = "日期";
                // 填充数据
                for (int i = 0; i < list.Count; i++)
                {
                    for (int j = 0; j < properties.Length; j++)
                    {
                        worksheet.Cells[i + 2, j + 1] = properties[j].GetValue(list[i], null);
                    }
                }
                // 设置格式
                Excel.Range range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[list.Count + 1, properties.Length]];
                range.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
                range.Borders.Weight = Excel.XlBorderWeight.xlThin;
                range.Columns.AutoFit();
                // 设置第一列文字居中
                Excel.Range firstColumnRange = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[list.Count + 1, 1]];
                firstColumnRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                // 保存Excel文件
                workbook.SaveAs(path);
                workbook.Close();
                excel.Quit();
            }
            catch (Exception ex)
            {
                Logger.Error("生成报表异常:" + ex.Message);
                result = false;
            }
            return result;
        }

感兴趣的可以关注“墨水直达”公众号,提供了许多免费插件供你使用

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值