12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382 |
- 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;
- using PaintDotNet.Base.CommTool;
- namespace Metis.AutoAnalysis
- {
- /// <summary>
- /// word和excel操作类
- /// </summary>
- public static class OfficeFileOperater
- {
- 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(AutoAnalyzeSettingModel analyzeSettingModel, List<List<string>> contentList, List<Bitmap> bitmapList,
- Dictionary<string, string> tagPositionDic, bool isNeedZoom, double pointPitch, double unitLength, decimal gainMultiple, string lblResult, 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,lblResult);
- }
- }
- /// <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(AutoAnalyzeSettingModel analyzeSettingModel, Dictionary<string, string> tagValueDic, List<Bitmap> bitmapList, double pointPitch, double unitLength, decimal gainMultiple, string lblResult)
- {
- 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 == "customerName")
- bk.Range.Text = analyzeSettingModel.customerName;
- else if (bk.Name == "telephone")
- bk.Range.Text = analyzeSettingModel.telephone;
- else if (bk.Name == "sampleName")
- bk.Range.Text = analyzeSettingModel.sampleName;
- else if (bk.Name == "sampleDescription")
- bk.Range.Text = analyzeSettingModel.sampleDescription;
- else if (bk.Name == "checkItem")
- bk.Range.Text = analyzeSettingModel.checkItem;
- else if (bk.Name == "methodStandard")
- bk.Range.Text = analyzeSettingModel.methodStandard;
- else if (bk.Name == "receiveDate")
- bk.Range.Text = analyzeSettingModel.receiveDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "checkDate")
- bk.Range.Text = analyzeSettingModel.checkDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "reportDate")
- bk.Range.Text = analyzeSettingModel.reportDate.ToString("yyyy/MM/dd");
- else if (bk.Name == "reportNumber")
- bk.Range.Text = analyzeSettingModel.reportNumber;
- else if (bk.Name == "checkRegion")
- bk.Range.Text = analyzeSettingModel.checkRegion;
- else if (bk.Name == "checkEnvironment")
- bk.Range.Text = analyzeSettingModel.checkEnvironment;
- else if (bk.Name == "level")
- bk.Range.Text = lblResult;
- 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);
- }
- try
- {
- //缩放的Bitmap尺寸
- int new_w = (int)bitmap.Width / 4;
- int new_h = (int)bitmap.Height / 4;
- Bitmap b = new Bitmap(new_w,new_h);
- Graphics g = Graphics.FromImage(b);
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
- g.DrawImage(bitmap,new System.Drawing.Rectangle(0,0,new_w,new_h),new System.Drawing.Rectangle(0,0,bitmap.Width,bitmap.Height),GraphicsUnit.Pixel);
- //通过粘贴板的方式可以不使用本地图片
- Clipboard.SetDataObject(b);
- bk.Range.Paste();
- b.Dispose();
- g.Dispose();
- }
- catch(Exception e)
- {
- string m = e.Message;
- }
-
- //控制插入word图片大小
- m_doc.InlineShapes[1].Width = targetWidth;
- m_doc.InlineShapes[1].Height = targetHeight;
- }
- }
- }
- 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>
- /// 导出结果(一个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;*/
- }
- }
- }
|