引用:Spire.XLS 是一个 Excel 文件的读写库,无需安装office,使用起来也挺方便的。Spire还有一些其他的库(Spire.Doc,Spire.Pdf……)
说明:Spire.XLS.dll还会实例化Spire.Pdf.dll中的类,所以Spire.XLS.dll ,Spire.Pdf.dll ,Spire.License.dll 这3个dll一起使用
Excel转图片:
//初始化一个Workbook实例,并加载一个工作簿文件 Workbook workbookExcel = new Workbook(); workbookExcel.LoadFromFile(paramSourceBookPath);//路径 //循环将工作表保存为图片 if (workbookExcel != null) { for (int i = 0; i < workbookExcel.Worksheets.Count; i++) { string pngPath = pngDirectoryName + "\" + (i + 1).ToString() + ".png"; Worksheet sheet = workbookExcel.Worksheets[i]; sheet.SaveToImage(pngPath); sheet.Clear(); Thread.Sleep(100); CaptureImage(pngPath, 0, 50, pngPath);//截取图片,去掉版本信息 } }
试用版的spire.xls在转换时,会在文件中加入一个版本信息:Evaluation Warning : The document wascreated with Spire.XLS for .NET,去掉这个信息,我直接截取图片了
/// <summary> /// 截取图片(去掉版本信息:Evaluation Warning : The document wascreated with Spire.XLS for .NET) /// </summary> /// <param name="fromImagePath"></param> /// <param name="offsetX"></param> /// <param name="offsetY"></param> /// <param name="toImagePath"></param> public void CaptureImage(string fromImagePath, int offsetX, int offsetY, string toImagePath) { //原图片文件 Image fromImage = Image.FromFile(fromImagePath); int width = fromImage.Width; int height = fromImage.Height - offsetY; //创建新图位图 Bitmap bitmap = new Bitmap(width, height); //创建作图区域 Graphics graphic = Graphics.FromImage(bitmap); //截取原图相应区域写入作图区 graphic.DrawImage(fromImage, 0, 0, new Rectangle(offsetX, offsetY, width, height), GraphicsUnit.Pixel); //从作图区生成新图 Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap()); //释放资源 graphic.Dispose(); bitmap.Dispose(); fromImage.Dispose(); FileInfo oldImage = new FileInfo(fromImagePath); if (oldImage.Exists) { global::System.IO.File.Delete(fromImagePath); } //保存图片 saveImage.Save(toImagePath, System.Drawing.Imaging.ImageFormat.Png); //释放资源 saveImage.Dispose(); }
Excel转其他格式文件:
// 源文件路径 string sourceFilePath = OpenFile.FileName; SaveFileDialog saveFileDialog = new SaveFileDialog(); switch (fileFormat) { case FileFormat.Bitmap: saveFileDialog.Filter = "Bitmap(*.bmp)|*.bmp"; break; case FileFormat.PDF: saveFileDialog.Filter = "PDF Document(*.pdf)|*.pdf"; break; case FileFormat.ODS: saveFileDialog.Filter = "OpenOffice Document Spreadsheet(*.ods)|*.ods"; break; case FileFormat.CSV: saveFileDialog.Filter = "CSV(*.csv)|*.csv"; break; case FileFormat.XML: saveFileDialog.Filter = "XML(*.xml)|*.xml"; break; case FileFormat.XPS: saveFileDialog.Filter = "XPS(*.xps)|*.xps"; break; case FileFormat.Version2007: saveFileDialog.Filter = "XPS(*.xps)|*.xps"; break; default: break; } saveFileDialog.FilterIndex = 0; if (saveFileDialog.ShowDialog() != DialogResult.OK) return; // 转换后的目标文件路径 string destFilePath = saveFileDialog.FileName; // 转换 Workbook workbook = new Workbook(); workbook.LoadFromFile(sourceFilePath); workbook.SaveToFile(destFilePath, fileFormat);