1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.Office.Interop.Excel;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using Microsoft.Office.Core;
  9.  
  10. namespace HustCAD.IntePLM.Win.BatchEnterWinUI
  11. {
  12. public class SighExcel
  13. {
  14. #region DllImport Methods
  15. [System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
  16. public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
  17. #endregion
  18.  
  19. Microsoft.Office.Interop.Excel.ApplicationClass application = null;
  20. Microsoft.Office.Interop.Excel.Workbook workBook = null;
  21. Microsoft.Office.Interop.Excel.Worksheet wSheet = null;
  22.  
  23. /// <summary>
  24. /// 对EXCEL指定单元格进行操作
  25. /// </summary>
  26. /// <param name="filePath">EXCEL表格所在路径</param>
  27. /// <param name="row">行号</param>
  28. /// <param name="column">列号</param>
  29. /// <param name="code">内容</param>
  30. /// <returns></returns>
  31. public bool signExcel(string filePath, int row, int column, string code)
  32. {
  33. System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  34. System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
  35.  
  36. object missing = Type.Missing;
  37. try
  38. {
  39. try
  40. {
  41. application = new Microsoft.Office.Interop.Excel.ApplicationClass();
  42. }
  43. catch (Exception e)
  44. {
  45. System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  46. }
  47. if (application == null)
  48. {
  49. System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  50. }
  51.  
  52. application.AlertBeforeOverwriting = false;
  53. application.AskToUpdateLinks = false;
  54. application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
  55. application.DisplayAlerts = false;
  56.  
  57. workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
  58. true, missing, missing, missing, missing, missing, missing, missing, missing);
  59. workBook.CheckCompatibility = false;//兼容性检查
  60. workBook.DoNotPromptForConvert = true;
  61.  
  62. wSheet = (Worksheet)workBook.Worksheets[1];
  63. wSheet.Cells[row, column] = code;
  64. Microsoft.Office.Interop.Excel.Range rtemp = wSheet.get_Range(wSheet.Cells[3, 4], wSheet.Cells[3, 6]);
  65. rtemp.Font.Name = "宋体";
  66. rtemp.Font.Size = 12;
  67. object RouteWorkbook = false;
  68. object SaveChanges = XlSaveAction.xlSaveChanges;
  69. //wBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  70. workBook.Save();
  71. workBook.Close(SaveChanges, filePath, RouteWorkbook);
  72. return true;
  73. }
  74. catch (Exception e)
  75. {
  76. System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  77. return false;
  78. }
  79. finally
  80. {
  81. if (workBook != null)
  82. {
  83. workBook.Close(true, missing, missing);
  84. workBook = null;
  85. }
  86. if (application != null)
  87. {
  88. application.Quit();
  89. KillSpecialExcel(application);
  90. application = null;
  91. }
  92. GC.Collect();
  93. GC.WaitForPendingFinalizers();
  94. GC.Collect();
  95. GC.WaitForPendingFinalizers();
  96. }
  97. }
  98.  
  99. /// <summary>
  100. /// Kill Special Excel Process
  101. /// </summary>
  102. public static void KillSpecialExcel(Application m_objExcel)
  103. {
  104. try
  105. {
  106. if (m_objExcel != null)
  107. {
  108. int lpdwProcessId;
  109. GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
  110. System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
  111. }
  112. }
  113. catch (Exception)
  114. {}
  115. }
  116.  
  117. public string getCellValue(string filePath, int row, int column)
  118. {
  119. System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  120. System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
  121.  
  122. object missing = Type.Missing;
  123. try
  124. {
  125. try
  126. {
  127. application = new Microsoft.Office.Interop.Excel.ApplicationClass();
  128. }
  129. catch (Exception e)
  130. {
  131. System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  132. }
  133. if (application == null)
  134. {
  135. System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  136. }
  137.  
  138. application.AlertBeforeOverwriting = false;
  139. application.AskToUpdateLinks = false;
  140. application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
  141. application.DisplayAlerts = false;
  142.  
  143. workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
  144. true, missing, missing, missing, missing, missing, missing, missing, missing);
  145. workBook.CheckCompatibility = false;//兼容性检查
  146. workBook.DoNotPromptForConvert = true;
  147.  
  148. wSheet = (Worksheet)workBook.Worksheets[1];
  149. return ((Microsoft.Office.Interop.Excel.Range)wSheet.Cells[row, column]).Text.ToString().Trim();
  150. }
  151. catch (Exception e)
  152. {
  153. System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  154. return "";
  155. }
  156. finally
  157. {
  158. if (workBook != null)
  159. {
  160. workBook.Close(true, missing, missing);
  161. workBook = null;
  162. }
  163. if (application != null)
  164. {
  165. application.Quit();
  166. KillSpecialExcel(application);
  167. application = null;
  168. }
  169. GC.Collect();
  170. GC.WaitForPendingFinalizers();
  171. GC.Collect();
  172. GC.WaitForPendingFinalizers();
  173. }
  174. }
  175.  
  176. /// <summary>
  177. /// 得到当前程序的路径
  178. /// </summary>
  179. /// <returns></returns>
  180. static public string GetCurrentPath()
  181. {
  182. string asstring = Assembly.GetExecutingAssembly().Location;
  183. string[] aa = asstring.Split('\\');
  184. string path = string.Empty;
  185. foreach (string var in aa)
  186. {
  187. if (var != aa[aa.Length - 1])
  188. path += var + @"\";
  189. }
  190. return path;
  191. }
  192. }
  193. }

  

C#实现对EXCEL指定单元格进行操作的更多相关文章

  1. 使用VBA将Excel指定单元格数据、字符串或者图表对象插入到Word模板指定书签处

    准备工作: 1.首先需要提供一个word模板,并且标记好您要插入书签的位置,定义书签的命名.如图 2.模拟您要插入的Excel原始数据和图表对象 插入代码如下: Private Sub Command ...

  2. C#修改 Excel指定单元格的值

    /// <summary> /// 将指定字符串写入指定单元格中 /// </summary> /// <param name="data">要 ...

  3. ASP.NET 导出gridview中的数据到Excel表中,并对指定单元格换行操作

    1. 使用NPOI读取及生成excel表. (1)导出Click事件: 获取DataTable; 给文件加文件名: string xlsxName = "xxx_" + DateT ...

  4. c#在Excel指定单元格中插入图片

    方法一: /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度./// 注意:图片必须是绝对物理路径/// </summary>/// <param name="R ...

  5. NPOI插入图片到excel指定单元格

    先看效果图 下载NPOI组件(2.0以上支持.xlsx和.xls的excel,2.0以下只支持.xls) NPOI下载官网http://npoi.codeplex.com 下载解压,里面有个dotne ...

  6. C# 插入条码到Excel指定单元格

    .NET中Barcode Library的应用二 介绍 在上一篇中我已经简单介绍了这个函数库(条形码应用之一------------函数库的简介).在这一篇中我将使用这个库提供更多的操作,希望对大家有 ...

  7. excel 截取单元格部分内容(从指定位置截取)

      excel 截取单元格部分内容(从指定位置截取) CreateTime--2018年5月28日08:28:46 Author:Marydon 1.情景展示 截取手机号后6位 2.实现 语法说明:r ...

  8. excel判断单元格包含指定内容的函数用=IF(COUNTIF(A1,"*内容*"),"0","1")

    前面我们聊过怎样将Excel包含某字符的单元格填充颜色,这边我们用另外一种方法来实现:excel判断单元格包含指定内容的函数 选中需要显示结果的单元格,假设我们要判断第一行第一列的单元格A1是否含有“ ...

  9. vba打开excel文件遍历sheet的名字和指定单元格的值

    今天项目上有个应用,获取指定Excel文件下的所有sheet的名称以及当前sheet中指定单元格的值,并把他们写到固定的sheet中去,看了下,文件比较多,而且每个文件sheet的个数比较多,也不一样 ...

随机推荐

  1. C# 自定义颜色

    一.需要引用 using System.Windows.Media; 二. 自定义颜色 通过自定义 RGB 的值来达到自定义颜色的目的 Color _Mycolor = Color.FromRgb(5 ...

  2. 1.JasperReports学习笔记1-了解JasperReports

    转自:http://www.blogjava.net/vjame/archive/2013/10/12/404908.html JasperReports是一个开源的java报表制作引擎,官网地址:h ...

  3. Learning Python 002 print() 和 input()

    Python print() 和 input() print()函数 print()函数可以向终端中输入指定的内容. 输出当个字符串 .py文件中,输入下面的代码,并保存: print('hello ...

  4. Jmeter连接MySQL配置(能执行多条sql语句)

    Database URL为MySQL的连接串,如果要执行多条SQL语句,后面还要添加“?allowMultiQueries=true”

  5. Luogu 4768 [NOI2018]归程

    并不会写Kruskal重构树,两个$log$跑得比较卡. 首先考虑一下没有强制在线的要求怎么办,有一个比较容易想到的做法就是先跑一遍最短路,然后把所有边按照海拔从大到小排序,把所有询问的海拔也从大到小 ...

  6. MQTT协议实现Eclipse Paho学习总结二

    一.概述 前一篇博客(MQTT协议实现Eclipse Paho学习总结一) 写了一些MQTT协议相关的一些概述和其实现Eclipse Paho的报文类别,同时对心跳包进行了分析.这篇文章,在不涉及MQ ...

  7. MySQL 文件导入出错

    ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot exec ...

  8. Java Script 学习笔记 -- jQuery

    一 jquery简介 1 jquery是什么  jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team. jQuery是继prototyp ...

  9. nginx配置同一域名下,共存2个nodejs项目

    项目背景: 1.官网需要改版,使用nodejs nuxt框架进行重构 2.官网改版没有全部完成.但需要上线首页 项目需求: 1.让首页内容显示为新项目 2.让老官网的内容可以被访问到(比如www.n. ...

  10. java进阶——反射(Reflect)

    一.Class类 1.类是对象,类是java.lang.Class类的实例对象,这个对象称为该类的类类型: 2.任何一个类都是Class的实例对象,类的表达式: (1)Class c1 = int.C ...