123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413 |
- using System;
- using System.Collections.Generic;
- using MSWord = Microsoft.Office.Interop.Word;
- using MSExcel = Microsoft.Office.Interop.Excel;
- using System.IO;
- using PaintDotNet.Base.Functionodel;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- using System.Drawing;
- using System.Text.RegularExpressions;
- using Microsoft.Office.Interop.Excel;
- using System.Reflection;
- using Microsoft.Office.Core;
- namespace PaintDotNet.Base.CommTool
- {
- /// <summary>
- /// word和excel操作类
- /// </summary>
- public static class OfficeFileHandleHelper
- {
- private static Object missing = Type.Missing;
- private static MSWord.Application m_word;
- private static MSWord.Document m_doc;
- private static MSExcel.Application m_excel;
- private static MSExcel.Workbook m_workbook;
- private static MSExcel.Worksheet m_worksheet;
- private static MSExcel.Worksheet m3_worksheet;
- private static MSExcel.Worksheet m2_worksheet;
- public static System.Data.DataTable calipersTable; //颗粒统计-卡规设置
- /// <summary>
- /// 打开word和excel文档
- /// </summary>
- /// <param name="filePath"></param>
- public static bool OpenOfficeFile(string filePath)
- {
- bool isSucceed = false;//打开是否成功
- int fileType = FileOperationHelper.IsFileWordOrExcel(filePath);
- //word文档
- if (fileType == 1)
- {
- try
- {
- m_word = new MSWord.Application();
- Object fileName = filePath;
- m_word.Documents.Open(ref fileName,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing);
- m_word.Visible = true;
- isSucceed = true;
- m_word = null;
- }
- catch (Exception)
- {
- //如果文件之前已打开,且拒绝再次使用只读模式打开
- //属于打开文件失败,但word程序已创建,将该程序关闭
- if(m_word != null)
- {
- m_word.Visible = false;
- m_word.Quit(false, ref missing, ref missing);
- m_word = null;
- }
-
- //用户手动取消"打开已打开文件的副本",会进入该判断
- //if (e.Message == "命令失败")
- // return true;
- isSucceed = false;
- }
- }
- //excel文档
- else if (fileType == 2)
- {
- try
- {
- m_excel = new MSExcel.Application();
- m_excel.Workbooks.Open(filePath);
- m_excel.Visible = true;
- isSucceed = true;
- }
- catch (Exception)
- {
- if (m_excel != null)
- {
- m_excel.DisplayAlerts = false;
- m_excel.Visible = false;
- }
- isSucceed = false;
- }
- m_excel = null;
- }
- //其他
- else
- {
-
- }
- return isSucceed;
- }
- /// <summary>
- /// 新建空白word文档
- /// </summary>
- /// <param name="dictPath">保存路径</param>
- /// <param name="filePath">文件全路径</param>
- /// <param name="opened">是否自动打开</param>
- /// <returns></returns>
- public static bool CreateNewWordFile(string dictPath, string filePath, bool isOpened)
- {
- //路径不存在则创建
- if (!Directory.Exists(dictPath))
- Directory.CreateDirectory(dictPath);
- try
- {
- m_word = new MSWord.Application();
- Object savePath = filePath;
- m_doc = m_word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
- m_doc.SaveAs2(ref savePath,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing);
- if (isOpened)
- m_word.Visible = true;//画面上是否可见
- else
- {
- m_doc.Close(false, ref missing, ref missing);
- m_word.Quit(false, ref missing, ref missing);
- }
- m_word = null;
- m_doc = null;
- return true;
- }
- catch(Exception)
- {
- if(m_word != null)
- {
- if(m_doc != null)
- {
- m_doc.Close(false, ref missing, ref missing);
- m_doc = null;
- }
- m_word.Visible = false;
- m_word.Quit(false, ref missing, ref missing);
- m_word = null;
- }
- return false;
- }
- }
- /// <summary>
- /// 新建空白excel文档
- /// </summary>
- /// <param name="dictPath">保存路径</param>
- /// <param name="filePath">文件全路径</param>
- /// <param name="opened">是否自动打开</param>
- /// <returns></returns>
- public static bool CreateNewExcelFile(string dictPath, string filePath, bool isOpened)
- {
- //路径不存在则创建
- if (!Directory.Exists(dictPath))
- Directory.CreateDirectory(dictPath);
- try
- {
- m_excel = new MSExcel.Application();
- m_workbook = m_excel.Workbooks.Add(true);
- for (int i = 0; i < 2; i++)
- {
- m_workbook.Worksheets.Add(After: m_workbook.Sheets.get_Item(m_workbook.Sheets.Count));
- }
- m_workbook.SaveAs(filePath, missing, missing, missing, missing, missing, MSExcel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing);
- }
- catch (Exception e)
- {
- throw e;
- }
- finally
- {
- if (m_excel != null)
- {
- if (m_workbook != null)
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- }
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- }
- return true;
- }
- #region 新的分析报告通用方法-word中的图片定倍显示
- /// <summary>
- /// 生成分析报告
- /// </summary>
- /// <param name="analyzeSettingModel">基础信息对象</param>
- /// <param name="contentList">数据对象模型</param>
- /// <param name="bitmapList">图片集合</param>
- /// <param name="tagPositionDic">除基础信息外的word书签与excel坐标对应信息</param>
- /// <param name="pointPitch">当前图片放大倍数</param>
- /// <param name="unitLength">当前图片标尺</param>
- /// <param name="gainMultiple">系统激活放大倍数(暂时不用保留)</param>
- public static void CreateAnalysisReport(AnalyzeSettingModel analyzeSettingModel, List<List<string>> contentList, List<Bitmap> bitmapList,
- Dictionary<string, string> tagPositionDic, bool isNeedZoom, double pointPitch, double unitLength, decimal gainMultiple, string dictPath = null, Dictionary<string, string> pNames = null, List<List<string>> content2List = null)
- {
- string saveAsPath = "";
- string excelModulePath = Path.GetDirectoryName(analyzeSettingModel.modulePath) + "\\公式.xlsx";//获取excel公式模板的路径
- if (File.Exists(excelModulePath))
- {
- saveAsPath = analyzeSettingModel.savePath + "\\" + analyzeSettingModel.analyzeClassify //+ "分析"
- + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";//另存的excel文件名
- //如果savePath是盘符不是文件夹,会多出一个斜杠,office的saveas无法识别,固需处理一下
- if (saveAsPath.IndexOf("\\\\") != -1)
- saveAsPath = saveAsPath.Replace("\\\\", "\\");
- if (contentList != null)
- {
- SaveAsExcelWithModule(excelModulePath, saveAsPath, contentList, dictPath, pNames, content2List);
- }
- Dictionary<string, string> tagValueDic = GetContentFromExcel(saveAsPath, tagPositionDic);
- CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, pointPitch, unitLength, gainMultiple);
- }
- }
- /// <summary>
- /// 生成分析报告并保存图片与中间数据
- /// </summary>
- /// <param name="analyzeSettingModel"></param>
- /// <param name="contentList"></param>
- /// <param name="dataList">中间数据</param>
- /// <param name="bitmapList"></param>
- /// <param name="tagPositionDic"></param>
- /// <param name="newPath"></param>
- /// <param name="newCode"></param>
- public static void CreateAnalysisReport(AnalyzeSettingModel analyzeSettingModel, List<List<string>> contentList, List<ExportProjectModel> dataList,
- List<Bitmap> bitmapList, Dictionary<string, string> tagPositionDic, string newPath, string newCode, bool isNeedZoom, double pointPitch, double unitLength, decimal gainMultiple, string dictPath, Dictionary<string, string> pNames, List<List<string>> content2List)
- {
- string saveAsPath = "";
- string excelModulePath = Path.GetDirectoryName(analyzeSettingModel.modulePath) + "\\公式.xlsx";//获取excel公式模板的路径
- if (File.Exists(excelModulePath))
- {
- saveAsPath = newPath + "\\" + newCode + ".xlsx";//另存的excel文件名
- //如果savePath是盘符不是文件夹,会多出一个斜杠,office的saveas无法识别,固需处理一下
- if (saveAsPath.IndexOf("\\\\") != -1)
- saveAsPath = saveAsPath.Replace("\\\\", "\\");
- if (SaveAsExcelWithModule(excelModulePath, saveAsPath, contentList, dictPath, pNames, content2List))
- {
- //保存中间数据
- string tempDataPath = newPath + "\\" + newCode + "_1.xlsx"; //"-中间数据" + ".xlsx";
- if (tempDataPath.IndexOf("\\\\") != -1)
- tempDataPath = tempDataPath.Replace("\\\\", "\\");
- SaveTempDataToExcel(tempDataPath, dataList);
- Dictionary<string, string> tagValueDic = GetContentFromExcel(saveAsPath, tagPositionDic);
- //if (isNeedZoom)
- //{
- // List<Bitmap> zoomList = new List<Bitmap>();
- // for (int i = 0; i < bitmapList.Count; i++)
- // {
- // zoomList.Add(GetFixedMultipleBitmap(bitmapList[i], pointPitch, unitLength, gainMultiple));
- // }
- // CreateNewWordWithContent(analyzeSettingModel, tagValueDic, zoomList, newPath, newCode);
- //}
- //else
- //{
- // CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, newPath, newCode);
- //}
- CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, newPath, newCode);
- //保存图片
- SaveAllImage(bitmapList, newPath, newCode);
- }
- }
- }
- /// <summary>
- /// 返回定倍(A4纸)显示后的图片
- /// 定倍计算公式:图片像素(宽和高) * 当前图片标尺 * 当前图片放大倍数
- /// </summary>
- /// <param name="oldBit"></param>
- /// <param name="pointPitch">当前图片放大倍数</param>
- /// <param name="unitLength">当前图片标尺</param>
- /// <param name="gainMultiple">系统激活标尺放大倍数(暂时没用)</param>
- /// <returns></returns>
- private static Bitmap GetFixedMultipleBitmap(Bitmap oldBit, double pointPitch, double unitLength, decimal gainMultiple)
- {
- if (pointPitch == 0)
- return oldBit;
- int oldWidth = oldBit.Width;
- int oldHeight = oldBit.Height;
- int targetWidth = 0;
- int targetHeight = 0;
- if (oldWidth <= 1 || oldHeight <= 1)//像素最小为1,之后不再处理
- return oldBit;
- //点距定倍注释
- //double pantographRatio = unitLength / pointPitch;//缩放比
- //double pantographRatio = unitLength * (double)gainMultiple;//标尺*放大倍数
- //double aspectRatio = oldWidth / (oldHeight * 1d);//宽高比
- //if (oldWidth <= oldHeight)
- //{
- // //targetWidth = (int)(oldWidth * pantographRatio * (double)gainMultiple);
- // // 定倍(A4)计算公式:图片像素(宽) * 当前图片标尺 * 当前图片放大倍数
- // targetWidth = (int)(oldWidth * pantographRatio) ;
- // if (targetWidth < 1 || targetWidth > oldWidth)//像素值异常不做处理
- // return oldBit;
- // targetHeight = (int)(targetWidth / aspectRatio);
- //}
- //else
- //{
- // //点距定倍注释
- // //targetHeight = (int)(oldHeight * pantographRatio * (double)gainMultiple);
- // // 定倍(A4)计算公式:图片像素(高) * 当前图片标尺 * 当前图片放大倍数
- // targetHeight = (int)(oldHeight * pantographRatio);
- // if (targetHeight < 1 || targetHeight > oldHeight)//像素值异常不做处理
- // return oldBit;
- // targetWidth = (int)(targetHeight * aspectRatio);
- //}
- //缩放图片
- Bitmap targetBit = new Bitmap(oldWidth, oldHeight);
- Graphics g = Graphics.FromImage(targetBit);
- g.DrawImage(oldBit, new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight), new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight), GraphicsUnit.Pixel);
- return targetBit;
- }
- #endregion
- private static string NunToChar(int number)
- {
- if (65 <= number && 90 >= number)
- {
- System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
- byte[] btNumber = new byte[] { (byte)number };
- return asciiEncoding.GetString(btNumber);
- }
- return "数字不在转换范围内";
- }
- /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
- /// 注意:图片必须是绝对物理路径
- /// </summary>
- /// <param name="rng">Excel单元格选中的区域</param>
- /// <param name="PicturePath">要插入图片的绝对路径。</param>
- public static void InsertPicture(RectangleF rng, Microsoft.Office.Interop.Excel._Worksheet sheet, string PicturePath, string dictPath, Dictionary<string, string> pNames)
- {
- //rng.Select();
- float PicLeft, PicTop, PicWidth, PicHeight;
- try
- {
- PicLeft = rng.Left;// Convert.ToSingle(rng.Left);
- PicTop = rng.Top;// Convert.ToSingle(rng.Top);
- PicWidth = rng.Width;// Convert.ToSingle(rng.Width);
- PicHeight = rng.Height;// Convert.ToSingle(rng.Height);
- sheet.Shapes.AddPicture(PicturePath, MsoTriState.msoFalse, MsoTriState.msoTrue, PicLeft, PicTop, PicWidth, PicHeight);
- Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)sheet.Pictures(Type.Missing);
- string pName = PicturePath.Replace(dictPath + "\\", string.Empty);
- string pName1 = pName.Replace(".jpg", string.Empty);
- if (pics.Count > 0)
- {
- Picture pic = pics.Item(pics.Count) as Picture;
- string pName2;
- pNames.TryGetValue(pName1, out pName2);
- pic.Name = pName2;
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("错误:" + ex.Message);
- }
- }
- /// <summary>
- /// 通过公式模板创建并保存excel
- /// </summary>
- /// <param name="excelModulePath">excel公式模板路径</param>
- /// <param name="saveAsPath">新文件另存路径</param>
- /// <param name="contentList">数据对象模型</param>
- /// <returns></returns>
- public static bool SaveAsExcelWithModule(string excelModulePath, string saveAsPath, List<List<string>> contentList, string dictPath = null, Dictionary<string, string> pNames = null
- , List<List<string>> content2List = null)
- {
- try
- {
- m_excel = new MSExcel.Application();
- m_workbook = m_excel.Workbooks.Add(excelModulePath);
- m_worksheet = m_workbook.Sheets.Item[2];//数据固定插入在第二个sheet页
- MSExcel.Worksheet m_worksheet1 = m_workbook.Sheets.Item[1];//数据固定插入在第二个sheet页
- if (content2List != null)
- {
- if (m_workbook.Sheets.Count < 3)
- m_workbook.Sheets.Add(Missing.Value, m_worksheet, Missing.Value, Missing.Value);
- m2_worksheet = m_workbook.Sheets.Item[3];
- AddTableToExcelSheet(m2_worksheet, 1, 1, content2List);
- }
- if (dictPath != null)
- {
- Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet1.Pictures(Type.Missing);
- Dictionary<string, RectangleF> keyValuePairs = new Dictionary<string, RectangleF>();
- for (int i = 1; i <= pics.Count; i++)
- {
- //可以循环这个excel里面的图
- Picture pic = pics.Item(i) as Picture;
- ////可以获取图的左上cell
- //Range topleft = pic.Left;
- ////可以获取图的右下cell
- //Range rightbottom = pic.BottomRightCell;
- keyValuePairs.Add(pic.Name, new RectangleF((float)pic.Left, (float)pic.Top, (float)pic.Width, (float)pic.Height)/*m_worksheet1.get_Range(topleft, rightbottom)*/);
- }
- pics.Delete();
- foreach (string d in Directory.GetFileSystemEntries(dictPath))
- {
- string pName = d.Replace(dictPath + "\\", string.Empty);
- string pName1 = pName.Replace(".jpg", string.Empty);
- RectangleF/*Microsoft.Office.Interop.Excel.Range*/ range;
- keyValuePairs.TryGetValue(pName1, out range);
- if (range != null)
- InsertPicture(range, m_worksheet1, d, dictPath, pNames);
- }
-
- }
- if (calipersTable != null)
- {
- if (m_workbook.Sheets.Count < 3)
- m_workbook.Sheets.Add(Missing.Value, m_worksheet, Missing.Value, Missing.Value);
- m3_worksheet = m_workbook.Sheets.Item[3];
- m3_worksheet.Name = "feret all";
- AddExportCalipersSheet(m3_worksheet, calipersTable);
- calipersTable = null;
- }
- AddTableToExcelSheet(m_worksheet, 1, 1, contentList);
- //if (content2List != null)
- // ((Worksheet)m_workbook.Sheets.Item[2]).Select();
-
- m_worksheet.SaveAs(saveAsPath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
- //m_worksheet.Activate();
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- m_worksheet = null;
- m2_worksheet = null;
- m_workbook = null;
- m_excel = null;
- }
- catch (Exception)
- {
- if (m_excel != null)
- {
- if (m_workbook != null)
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- }
- m_worksheet = null;
- m2_worksheet = null;
- m_workbook = null;
- m_excel = null;
- return false;
- }
- return true;
- }
- /// <summary>
- /// 保存中间数据excel
- /// </summary>
- /// <param name="savePath"></param>
- /// <param name="dataList"></param>
- /// <returns></returns>
- public static bool SaveTempDataToExcel(string savePath, List<ExportProjectModel> dataList)
- {
- if (dataList != null && dataList.Count > 0)
- {
- dataList.Reverse();
- try
- {
- m_excel = new MSExcel.Application();
- m_workbook = m_excel.Workbooks.Add(true);
- int sheetIndex = 0;
- foreach (ExportProjectModel model in dataList)
- {
- if (sheetIndex != 0)
- m_workbook.Sheets.Add();
- m_worksheet = m_workbook.Sheets.Item[1];
- //去掉名称的后缀,不然为sheet页命名会报错
- string worksheetName = model.picName;
- if (worksheetName.LastIndexOf(".") != -1)
- worksheetName = worksheetName.Remove(worksheetName.LastIndexOf("."));
- //捕获异常,设置sheet页命名太长等原因可能会报错
- Exception nameLengthExceed;
- do
- {
- try
- {
- nameLengthExceed = null;
- m_worksheet.Name = worksheetName;
- }
- catch (Exception e)
- {
- nameLengthExceed = e;
- worksheetName = worksheetName.Remove(worksheetName.Length - 1);
- }
- if (worksheetName.Length <= 0)
- throw nameLengthExceed;
- } while (nameLengthExceed != null);
- ////去掉名称的后缀,不然为sheet页命名会报错
- //if (model.picName.LastIndexOf(".") != -1)
- // m_worksheet.Name = model.picName.Remove(model.picName.LastIndexOf("."));
- //else
- // m_worksheet.Name = model.picName;
- AddTableToExcelSheet(m_worksheet, 1, 1, model.dataList);
- sheetIndex++;
- }
- m_worksheet.SaveAs(savePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- }
- catch (Exception)
- {
- if (m_excel != null)
- {
- if (m_workbook != null)
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- }
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- return false;
- }
- return true;
- }
- else
- return false;
- }
- /// <summary>
- /// 向excel的sheet页指定单元格插入文本
- /// </summary>
- /// <param name="worksheet">sheet页</param>
- /// <param name="x">插入初始位置横坐标</param>
- /// <param name="y">插入初始位置纵坐标</param>
- /// <param name="content">文本内容</param>
- public static void AddContentToExcelSheet(MSExcel.Worksheet worksheet, int x, int y, string content)
- {
- worksheet.Cells[x, y] = content;
- }
- /// <summary>
- /// 向excel的sheet页指定单元格插入表格(自行拼接的list形式)
- /// </summary>
- /// <param name="worksheet">sheet页</param>
- /// <param name="x">插入初始位置横坐标</param>
- /// <param name="y">插入初始位置纵坐标</param>
- /// <param name="contentList">表格对象</param>
- public static void AddTableToExcelSheet(MSExcel.Worksheet worksheet, int x, int y, List<List<string>> contentList)
- {
- if(contentList.Count > 0)
- {
- for (int i = x; i < contentList.Count + 1; i++)
- {
- List<string> rowContent = contentList[i - 1];
- if(rowContent.Count > 0)
- {
- for(int j = y; j < rowContent.Count + 1; j++)
- {
- worksheet.Cells[i, j] = rowContent[j - 1];
- }
- }
-
- }
- }
- }
- public static void AddExportCalipersSheet(MSExcel.Worksheet worksheet, System.Data.DataTable calipersTable)
- {
- if (calipersTable.Rows.Count > 0)
- {
- for (int i = 0; i < calipersTable.Columns.Count; i++)
- {
- worksheet.Cells[1, i + 1] = calipersTable.Columns[i].ColumnName;
- }
- for (int j = 0; j < calipersTable.Rows.Count; j++)
- {
- for (int k = 0; k < calipersTable.Columns.Count; k++)
- {
- worksheet.Cells[j + 2, k + 1] = calipersTable.Rows[j][k].ToString();
- }
- }
- }
- }
- /// <summary>
- /// 获取excel文档指定位置的内容
- /// </summary>
- /// <param name="savePath"></param>
- /// <param name="tagPositionDic"></param>
- /// <returns></returns>
- public static Dictionary<string, string> GetContentFromExcel(string savePath, Dictionary<string, string> tagPositionDic)
- {
- if (!File.Exists(savePath) || tagPositionDic==null)
- return null;
- else
- {
- try
- {
- Dictionary<string, string> tagValueDic = new Dictionary<string, string>();
- m_excel = new MSExcel.Application();
- m_workbook = m_excel.Workbooks.Add(savePath);
- m_worksheet = m_workbook.Sheets.Item[1];//公式固定在第一个sheet页
- foreach(KeyValuePair<string, string> kvp in tagPositionDic)
- {
- string cellContent = m_worksheet.Range[kvp.Value].Value[MSExcel.XlRangeValueDataType.xlRangeValueDefault] == null ? ""
- : Convert.ToString(m_worksheet.Range[kvp.Value].Value[MSExcel.XlRangeValueDataType.xlRangeValueDefault]);
- tagValueDic.Add(kvp.Key, cellContent);
- }
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- return tagValueDic;
- }
- catch(Exception)
- {
- if (m_excel != null)
- {
- if (m_workbook != null)
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- }
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- return null;
- }
- }
- }
- /// <summary>
- /// 通过模板创建word报告文档
- /// </summary>
- /// <param name="analyzeSettingModel"></param>
- /// <param name="tagValueDic"></param>
- /// <param name="bitmapList"></param>
- public static void CreateNewWordWithContent(AnalyzeSettingModel analyzeSettingModel, Dictionary<string, string> tagValueDic, List<Bitmap> bitmapList, double pointPitch, double unitLength, decimal gainMultiple)
- {
- if(File.Exists(analyzeSettingModel.modulePath) && Directory.Exists(analyzeSettingModel.savePath))
- {
- string newFilePath = analyzeSettingModel.savePath + "\\" + analyzeSettingModel.analyzeClassify +// "报告" +
- DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx";
- if (newFilePath.IndexOf("\\\\") != -1)
- newFilePath = newFilePath.Replace("\\\\", "\\");
- try
- {
- File.Copy(analyzeSettingModel.modulePath, newFilePath, true);
- }
- catch (Exception)
- {
- //MessageBox.Show("word模板文件已打开,请关闭后重试");
- return;
- }
-
- Object pathObj = newFilePath;
- try
- {
- m_word = new MSWord.Application();
- m_doc = m_word.Documents.Open(ref pathObj,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing);
- foreach (MSWord.Bookmark bk in m_doc.Bookmarks)
- {
- if (bk.Name == "itemNumber")
- bk.Range.Text = analyzeSettingModel.itemNumber;
- else if (bk.Name == "ratingDate")
- bk.Range.Text = analyzeSettingModel.ratingDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "inspectionPerson")
- bk.Range.Text = analyzeSettingModel.inspectionPerson;
- else if (bk.Name == "contact")
- bk.Range.Text = analyzeSettingModel.contact;
- else if (bk.Name == "inspectionDepartment")
- bk.Range.Text = analyzeSettingModel.inspectionDepartment;
- else if (bk.Name == "inspectionDate")
- bk.Range.Text = analyzeSettingModel.inspectionDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "other")
- {
- //
- if(analyzeSettingModel.otherList != null && analyzeSettingModel.otherList.Count > 0)
- {
- MSWord.Table m_table = m_doc.Tables.Add(bk.Range, analyzeSettingModel.otherList.Count + 1, 2, ref missing, ref missing);
- m_table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleThickThinLargeGap;
- m_table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
- m_table.Cell(1, 1).Range.Text = "名称";
- m_table.Cell(1, 2).Range.Text = "内容";
- for (int i = 0; i < analyzeSettingModel.otherList.Count; i++)
- {
- m_table.Cell(2 + i, 1).Range.Text = analyzeSettingModel.otherList[i].name;
- m_table.Cell(2 + i, 2).Range.Text = analyzeSettingModel.otherList[i].content;
- }
- }
- }
- else if (bk.Name == "picture")
- {
- if(bitmapList != null && bitmapList.Count > 0)
- {
- bitmapList.Reverse();
- for (int i = 0; i < bitmapList.Count; i++)
- {
- Bitmap bitmap = GetFixedMultipleBitmap(bitmapList[i], pointPitch, unitLength, gainMultiple);
- int oldWidth = bitmap.Width;
- int oldHeight = bitmap.Height;
- float targetWidth = 0;
- float targetHeight = 0;
- double pantographRatio = 0;
- if (bitmapList[i].Tag != null)
- {
- pantographRatio = (double)bitmapList[i].Tag;//标尺*放大倍数
- }
- else
- {
- pantographRatio = unitLength * (double)gainMultiple;//标尺*放大倍数
- }
- double aspectRatio = oldWidth / (oldHeight * 1d);//宽高比
- if (oldWidth <= oldHeight)
- {
- // 定倍(A4)计算公式:图片像素(宽) * 当前图片标尺 * 当前图片放大倍数
- targetWidth = (float)(28.35 * oldWidth * pantographRatio) / 10000; //将单位转换成磅
- targetHeight = (float)(targetWidth / aspectRatio);
- }
- else
- {
- // 定倍(A4)计算公式:图片像素(高) * 当前图片标尺 * 当前图片放大倍数
- targetHeight = (float)(28.35 * oldHeight * pantographRatio) / 10000;//将单位转换成磅
- targetWidth = (float)(targetHeight * aspectRatio);
- }
- //通过粘贴板的方式可以不使用本地图片
- Clipboard.SetDataObject(bitmap);
- bk.Range.Paste();
- //控制插入word图片大小
- m_doc.InlineShapes[1].Width = targetWidth;
- m_doc.InlineShapes[1].Height = targetHeight;
- //m_doc.InlineShapes[1].ScaleWidth = (float)Math.Ceiling(100 * (double)gainMultiple * unitLength / pointPitch);//缩小到40%,可用
- //m_doc.InlineShapes[1].ScaleWidth = (float)Math.Ceiling(100 * (double)gainMultiple * unitLength / pointPitch);
- ////需要本地图片,暂时不可用
- //bk.Range.InlineShapes.AddPicture(@"D:\工作资料\工作资料\微信图片_20210125090958.jpg", ref missing, ref missing, ref missing);
- //m_doc.InlineShapes[1].Width = 283.5f;
- //m_doc.InlineShapes[1].Height = 226.8f;
- }
- }
- //插入方式是向InlineShapes的最前面插入,后插图的图片下标在前
- //bk.Range.InlineShapes.AddPicture(@"C:\Users\Administrator\Pictures\Shadowlands_Cinematic03_4k.jpg", ref missing, ref missing, ref missing);
- //bk.Range.InlineShapes.AddPicture(@"C:\Users\Administrator\Pictures\456.jpg", ref missing, ref missing, ref missing);
- //Object picRange = bk.Range;
- //m_doc.InlineShapes.AddPicture(@"D:\工作资料\工作资料\微信图片_20210125090958.jpg", ref missing, ref missing, ref picRange);
- //m_doc.InlineShapes.AddPicture(@"D:\工作资料\工作资料\微信图片_20210125090958.jpg", ref missing, ref missing, ref picRange);
- //m_doc.InlineShapes[1].Width = 283.5f;//缩小到40%
- //m_doc.InlineShapes[1].Height = 226.8f;
- }
- else
- {
- if(tagValueDic != null && tagValueDic.Count > 0)
- {
- foreach (KeyValuePair<string, string> kvp in tagValueDic)
- {
- if (bk.Name == kvp.Key)
- {
- bk.Range.Text = kvp.Value;
- break;
- }
- }
- }
- }
- }
- m_doc.Save();
- m_doc.Close(true);
- m_word.Quit();
- }
- catch(Exception)
- {
- if(m_word != null)
- {
- if(m_doc != null)
- m_doc.Close(false);
- m_word.Quit();
- }
- }
- m_doc = null;
- m_word = null;
- }
- }
- /// <summary>
- /// 导出项目使用,与生成报告区别的是存储路径与命名
- /// </summary>
- /// <param name="analyzeSettingModel"></param>
- /// <param name="tagValueDic"></param>
- /// <param name="bitmapList"></param>
- /// <param name="newPath"></param>
- /// <param name="newCode"></param>
- public static void CreateNewWordWithContent(AnalyzeSettingModel analyzeSettingModel, Dictionary<string, string> tagValueDic, List<Bitmap> bitmapList,
- string newPath, string newCode)
- {
- if (File.Exists(analyzeSettingModel.modulePath) && Directory.Exists(newPath))
- {
- string newFilePath = newPath + "\\" + newCode + ".docx";
- if (newFilePath.IndexOf("\\\\") != -1)
- newFilePath = newFilePath.Replace("\\\\", "\\");
- try
- {
- File.Copy(analyzeSettingModel.modulePath, newFilePath, true);
- }
- catch (Exception)
- {
- return;
- }
- Object pathObj = newFilePath;
- try
- {
- m_word = new MSWord.Application();
- m_doc = m_word.Documents.Open(ref pathObj,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing,
- ref missing, ref missing, ref missing, ref missing, ref missing);
- foreach (MSWord.Bookmark bk in m_doc.Bookmarks)
- {
- if (bk.Name == "itemNumber")
- bk.Range.Text = analyzeSettingModel.itemNumber;
- else if (bk.Name == "ratingDate")
- bk.Range.Text = analyzeSettingModel.ratingDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "inspectionPerson")
- bk.Range.Text = analyzeSettingModel.inspectionPerson;
- else if (bk.Name == "contact")
- bk.Range.Text = analyzeSettingModel.contact;
- else if (bk.Name == "inspectionDepartment")
- bk.Range.Text = analyzeSettingModel.inspectionDepartment;
- else if (bk.Name == "inspectionDate")
- bk.Range.Text = analyzeSettingModel.inspectionDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "other")
- {
- if (analyzeSettingModel.otherList != null && analyzeSettingModel.otherList.Count > 0)
- {
- MSWord.Table m_table = m_doc.Tables.Add(bk.Range, analyzeSettingModel.otherList.Count + 1, 2, ref missing, ref missing);
- m_table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleThickThinLargeGap;
- m_table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
- m_table.Cell(1, 1).Range.Text = "名称";
- m_table.Cell(1, 2).Range.Text = "内容";
- for (int i = 0; i < analyzeSettingModel.otherList.Count; i++)
- {
- m_table.Cell(2 + i, 1).Range.Text = analyzeSettingModel.otherList[i].name;
- m_table.Cell(2 + i, 2).Range.Text = analyzeSettingModel.otherList[i].content;
- }
- }
- }
- else if (bk.Name == "picture")
- {
- if (bitmapList != null && bitmapList.Count > 0)
- {
- bitmapList.Reverse();
- for (int i = 0; i < bitmapList.Count; i++)
- {
- double pointPitch = 0;
- double unitLength = 0;
- decimal gainMultiple = 0;
- Bitmap bitmap = GetFixedMultipleBitmap(bitmapList[i], pointPitch, unitLength, gainMultiple);
- int oldWidth = bitmap.Width;
- int oldHeight = bitmap.Height;
- float targetWidth = 0;
- float targetHeight = 0;
- double pantographRatio = 0;
- if (bitmapList[i].Tag != null)
- {
- pantographRatio = (double)bitmapList[i].Tag;//标尺*放大倍数
- }
- else
- {
- pantographRatio = unitLength * (double)gainMultiple;//标尺*放大倍数
- }
- double aspectRatio = oldWidth / (oldHeight * 1d);//宽高比
- if (oldWidth <= oldHeight)
- {
- // 定倍(A4)计算公式:图片像素(宽) * 当前图片标尺 * 当前图片放大倍数
- targetWidth = (float)(28.35 * oldWidth * pantographRatio) / 10000; //将单位转换成磅
- targetHeight = (float)(targetWidth / aspectRatio);
- }
- else
- {
- // 定倍(A4)计算公式:图片像素(高) * 当前图片标尺 * 当前图片放大倍数
- targetHeight = (float)(28.35 * oldHeight * pantographRatio) / 10000;//将单位转换成磅
- targetWidth = (float)(targetHeight * aspectRatio);
- }
- //通过粘贴板的方式可以不使用本地图片
- Clipboard.SetDataObject(bitmap);
- bk.Range.Paste();
- //控制插入word图片大小
- m_doc.InlineShapes[1].Width = targetWidth;
- m_doc.InlineShapes[1].Height = targetHeight;
- ////通过粘贴板的方式可以补使用本地图片
- //Clipboard.SetDataObject(bitmapList[i]);
- //bk.Range.Paste();
- ////需要本地图片,暂时不可用
- ////bk.Range.InlineShapes.AddPicture(bitmapList[i].ToString(), ref missing, ref missing, ref missing);
- }
- }
- }
- else
- {
- if (tagValueDic != null && tagValueDic.Count > 0)
- {
- foreach (KeyValuePair<string, string> kvp in tagValueDic)
- {
- if (bk.Name == kvp.Key)
- {
- bk.Range.Text = kvp.Value;
- break;
- }
- }
- }
- }
- }
- m_doc.Save();
- m_doc.Close(true);
- m_word.Quit();
- }
- catch (Exception)
- {
- if (m_word != null)
- {
- if (m_doc != null)
- m_doc.Close(false);
- m_word.Quit();
- }
- }
- m_doc = null;
- m_word = null;
- }
- }
- /// <summary>
- /// 杀死进程
- /// </summary>
- /// <param name="hwnd"></param>
- /// <param name="ID"></param>
- /// <returns></returns>
- [DllImport("User32.dll", CharSet = CharSet.Auto)]
- public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
- public static void Kill(MSExcel.Application excel)
- {
- IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
- int k = 0;
- GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
- System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
- p.Kill(); //关闭进程k
- }
- /// <summary>
- /// excel英文位置转坐标-以后可能用到
- /// 如A1转为(1,1);
- /// </summary>
- /// <param name="columnName"></param>
- /// <returns></returns>
- public static System.Drawing.Point ExcelRangeToCell(string cell_positon)
- {
- string positionX = Regex.Replace(cell_positon, "[0-9]", "", RegexOptions.IgnoreCase);
- string positionY = Regex.Replace(cell_positon, "[A-Z]", "", RegexOptions.IgnoreCase);
- if (!Regex.IsMatch(positionX.ToUpper(), @"[A-Z]+"))
- return new System.Drawing.Point(0, 0);
- int index = 0;
- char[] chars = positionX.ToUpper().ToCharArray();
- for (int i = 0; i < chars.Length; i++)
- {
- index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
- }
- return new System.Drawing.Point(index, Convert.ToInt32(positionY));
- }
- /// <summary>
- /// 保存数据到execl
- /// </summary>
- /// <param name="excelModulePath">excel公式模板路径</param>
- /// <param name="saveAsPath">新文件另存路径</param>
- /// <param name="sheets">数据对象模型</param>
- /// <returns></returns>
- public static bool SaveDataToExcel(object Template, string saveAsPath, List<List<List<string>>> sheets)
- {
- try
- {
- m_excel = new MSExcel.Application();
- m_workbook = m_excel.Workbooks.Add(Template);
- for (int i = 0; i < sheets.Count; i++)
- {
- List<List<string>> data = sheets[i];
- if (m_workbook.Sheets.Count <= i)
- {
- m_workbook.Worksheets.Add(After: m_workbook.Sheets.get_Item(m_workbook.Sheets.Count));
- }
- m_worksheet = m_workbook.Sheets.Item[i + 1];
- AddTableToExcelSheet(m_worksheet, 1, 1, data);
- }
- m_workbook.SaveAs(saveAsPath, missing, missing, missing, missing, missing, MSExcel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing);
- }
- catch (Exception e)
- {
- throw e;
- }
- finally
- {
- if (m_excel != null)
- {
- if (m_workbook != null)
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- }
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- }
- return true;
- }
- /// <summary>
- /// 保存数据到execl
- /// </summary>
- /// <param name="excelModulePath">excel公式模板路径</param>
- /// <param name="saveAsPath">新文件另存路径</param>
- /// <param name="sheets">数据对象模型</param>
- /// <returns></returns>
- public static bool SaveDataToExcel(string saveAsPath, List<List<List<string>>> sheets)
- {
- return SaveDataToExcel(MSExcel.XlWBATemplate.xlWBATWorksheet,saveAsPath,sheets);
- }
- /// <summary>
- /// 生成分析报告(夹杂物)
- /// </summary>
- /// <param name="analyzeSettingModel">基础信息对象</param>
- /// <param name="contentList">数据对象模型</param>
- /// <param name="bitmapList">图片集合</param>
- /// <param name="tagPositionDic">除基础信息外的word书签与excel坐标对应信息</param>
- public static void CreateAnalysisReportInclusion(AnalyzeSettingModel analyzeSettingModel, List<List<List<string>>> sheets, List<Bitmap> bitmapList,
- Dictionary<string, string> tagPositionDic, double pointPitch, double unitLength, decimal gainMultiple)
- {
- string saveAsPath = "";
- string excelModulePath = Path.GetDirectoryName(analyzeSettingModel.modulePath) + "\\公式.xlsx";//获取excel公式模板的路径
- if (File.Exists(excelModulePath))
- {
- saveAsPath = analyzeSettingModel.savePath + "\\" + analyzeSettingModel.analyzeClassify + "分析"
- + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";//另存的excel文件名
- //如果savePath是盘符不是文件夹,会多出一个斜杠,office的saveas无法识别,固需处理一下
- if (saveAsPath.IndexOf("\\\\") != -1)
- saveAsPath = saveAsPath.Replace("\\\\", "\\");
- if (SaveDataToExcel(excelModulePath, saveAsPath, sheets))
- {
- Dictionary<string, string> tagValueDic = GetContentFromExcel(saveAsPath, tagPositionDic);
- CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, pointPitch, unitLength, gainMultiple);
- }
- }
- }
- /// <summary>
- /// 导出结果(一个sheet页)
- /// </summary>
- public static void ExportDataToExcel(string path, List<System.Data.DataTable> datas, bool multiSheet=false)
- {
- Worksheet workSheet = null;
- Workbook workBook = null;
- Workbooks workbooks = null;
- MSExcel.Application xlApp = null;
- try
- {
- xlApp = new MSExcel.Application();
- workbooks = xlApp.Workbooks;
- workBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
- if (multiSheet)
- {
- if (datas != null && datas.Count > 0)
- {
- int ka = 1;
- foreach (System.Data.DataTable dtb in datas)
- {
- if (ka > 1)
- {
- Sheets sheets = workBook.Worksheets;
- workSheet = (Worksheet)sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
- }
- else
- {
- workSheet = (Worksheet)workBook.Worksheets[1];
- }
- ka++;
- workSheet.Cells.NumberFormat = "@";
- for (int i = 0; i < dtb.Columns.Count; i++)
- {
- workSheet.Cells[1, i + 1] = dtb.Columns[i].ColumnName;
- }
- for (int j = 0; j < dtb.Rows.Count; j++)
- {
- for (int k = 0; k < dtb.Columns.Count; k++)
- {
- workSheet.Cells[j+2, k+1] = dtb.Rows[j][k].ToString();
- }
- }
- }
- }
- }
- else
- {
- workBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
- workSheet = (Worksheet)workBook.Worksheets[1];
- if (datas != null && datas.Count > 0)
- {
- int kk = 0;
- int jj = 0;
- foreach (System.Data.DataTable dtb in datas)
- {
- if (kk == 0)
- {
- for (int i = 0; i < dtb.Columns.Count; i++)
- {
- workSheet.Cells[1, i + 1] = dtb.Columns[i].ColumnName;
- }
- kk++;
- }
- for (int j = 0; j < dtb.Rows.Count; j++)
- {
- for (int k = 0; k < dtb.Columns.Count; k++)
- {
- workSheet.Cells[jj + 2, k + 1] = dtb.Rows[j][k].ToString();
- }
- jj++;
- }
- }
- }
- }
- object nothing = Type.Missing;
- workBook.SaveAs(path, nothing, nothing, nothing, nothing, nothing,
- MSExcel.XlSaveAsAccessMode.xlExclusive, nothing, nothing, nothing, nothing, nothing);
- }
- catch (Exception)
- {
-
- }
- finally
- {
- if (xlApp != null)
- {
- if (xlApp != null && workBook!=null)
- workBook.Close(false);
- xlApp.Quit();
- Kill(xlApp);
- }
- }
- }
- /// <summary>
- /// 保存图片到本地
- /// </summary>
- /// <param name="bitList"></param>
- public static void SaveAllImage(List<Bitmap> bitList, string newPath, string newCode)
- {
- if(bitList != null && bitList.Count > 0)
- {
- int originNum = 0;
- int codeNum = 0;
- for (int i = 0; i < bitList.Count; i++)
- {
- string bitPath = "";
- //分别为原图和处理后的图命名
- if(i % 2 == 0)
- {
- originNum++;
- bitPath = newPath + "//origin-" + originNum + ".jpg";
- }
- else
- {
- codeNum++;
- bitPath = newPath + "/" + newCode + "-" + codeNum + ".jpg";
- }
- bitList[i].Save(bitPath);
- }
- }
- }
- /// <summary>
- /// xls转xlsx 但是需要office激活,没测试
- /// </summary>
- /// <param name="path"></param>
- /// <param name="name"></param>
- public static bool ConvertWorkbook(string path, string name)
- {
- bool action = false;
- var app = new Microsoft.Office.Interop.Excel.Application { Visible = false };
- Workbook book = null;
- try
- {
- book = app.Workbooks.Open(path);
- }
- catch (Exception)
- {
- }
- if(book!=null)
- {
- //注意,新的文件名没后缀
- book.SaveAs(Filename: Path.GetDirectoryName(path) + "\\" + name, FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
- book.Close();
- action = true;
- }
- app.Quit();
- Kill(app);
- return action;
- }
- public static bool aaaaa()
- {
- try
- {
- m_excel = new MSExcel.Application();
- m_workbook = m_excel.Workbooks.Open("C:\\Users\\zyh\\Desktop\\111.xlsx");
- m_worksheet = m_workbook.Sheets.Item[2];//数据固定插入在第二个sheet页
- MSExcel.Worksheet m_worksheet1 = m_workbook.Sheets.Item[1];//数据固定插入在第二个sheet页
- Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet1.Pictures(Type.Missing);
- for (int i = 1; i <= pics.Count; i++)
- {
- //可以循环这个excel里面的图
- Picture pic = pics.Item(i) as Picture;
- //可以获取图的左上cell
- Range topleft = pic.TopLeftCell;
- //可以获取图的右下cell
- Range rightbottom = pic.BottomRightCell;
- /*Microsoft.Office.Interop.Excel.Range rng = m_worksheet.get_Range(topleft, rightbottom);
-
- pics.Left = (double)pic.Left;
- pics.Top = (double)pic.Top;
- pics.Width = (double)pic.Width;
- pics.Height = (double)pic.Height;*/
- pics.Select(pic).Insert("C:\\Users\\zyh\\Desktop\\d\\imgbox1.jpg", Type.Missing);
-
- }
- m_worksheet.SaveAs("C:\\Users\\zyh\\Desktop\\111.xlsx", missing, missing, missing, missing, missing, missing, missing, missing, missing);
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- }
- catch (Exception ex)
- {
- if (m_excel != null)
- {
- if (m_workbook != null)
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- }
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;
- return false;
- }
- return true;
- /*m_excel = new MSExcel.Application();
- m_excel.Workbooks.Open("C:\\Users\\zyh\\Desktop\\111.xlsx");
-
- m_worksheet = m_excel.Sheets.Item[1];
- Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet.Pictures(Type.Missing);
-
- for (int i=1; i<= pics.Count; i++)
- {
- //可以循环这个excel里面的图
- Picture pic = pics.Item(i) as Picture;
- //可以获取图的左上cell
- Range topleft = pic.TopLeftCell;
-
- //可以获取图的右下cell
- Range rightbottom = pic.BottomRightCell;
- Microsoft.Office.Interop.Excel.Range rng = m_worksheet.get_Range("A1", "B2");
- try
- {
- pics.Insert("C:/Users/zyh/Desktop/imgbox1.jpg", Type.Missing);
- pics.Left = (double)rng.Left;
- pics.Top = (double)rng.Top;
- pics.Width = (double)rng.Width;
- pics.Height = (double)rng.Height;
- }
- catch(Exception ex)
- {
- }
- }
- m_worksheet.SaveAs("C:/Users/zyh/Desktop/333.xlsx", missing, missing, missing, missing, missing, missing, missing, missing, missing);
- m_workbook.Close(false);
- m_excel.Application.Quit();
- Kill(m_excel);
- m_worksheet = null;
- m_workbook = null;
- m_excel = null;*/
- }
- }
- }
|