C#实现对EXCEL指定单元格进行操作
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Core; namespace HustCAD.IntePLM.Win.BatchEnterWinUI
{
public class SighExcel
{
#region DllImport Methods
[System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
#endregion Microsoft.Office.Interop.Excel.ApplicationClass application = null;
Microsoft.Office.Interop.Excel.Workbook workBook = null;
Microsoft.Office.Interop.Excel.Worksheet wSheet = null; /// <summary>
/// 对EXCEL指定单元格进行操作
/// </summary>
/// <param name="filePath">EXCEL表格所在路径</param>
/// <param name="row">行号</param>
/// <param name="column">列号</param>
/// <param name="code">内容</param>
/// <returns></returns>
public bool signExcel(string filePath, int row, int column, string code)
{
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); object missing = Type.Missing;
try
{
try
{
application = new Microsoft.Office.Interop.Excel.ApplicationClass();
}
catch (Exception e)
{
System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
}
if (application == null)
{
System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
} application.AlertBeforeOverwriting = false;
application.AskToUpdateLinks = false;
application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
application.DisplayAlerts = false; workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
true, missing, missing, missing, missing, missing, missing, missing, missing);
workBook.CheckCompatibility = false;//兼容性检查
workBook.DoNotPromptForConvert = true; wSheet = (Worksheet)workBook.Worksheets[1];
wSheet.Cells[row, column] = code;
Microsoft.Office.Interop.Excel.Range rtemp = wSheet.get_Range(wSheet.Cells[3, 4], wSheet.Cells[3, 6]);
rtemp.Font.Name = "宋体";
rtemp.Font.Size = 12;
object RouteWorkbook = false;
object SaveChanges = XlSaveAction.xlSaveChanges;
//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);
workBook.Save();
workBook.Close(SaveChanges, filePath, RouteWorkbook);
return true;
}
catch (Exception e)
{
System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
return false;
}
finally
{
if (workBook != null)
{
workBook.Close(true, missing, missing);
workBook = null;
}
if (application != null)
{
application.Quit();
KillSpecialExcel(application);
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
} /// <summary>
/// Kill Special Excel Process
/// </summary>
public static void KillSpecialExcel(Application m_objExcel)
{
try
{
if (m_objExcel != null)
{
int lpdwProcessId;
GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
}
catch (Exception)
{}
} public string getCellValue(string filePath, int row, int column)
{
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); object missing = Type.Missing;
try
{
try
{
application = new Microsoft.Office.Interop.Excel.ApplicationClass();
}
catch (Exception e)
{
System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
}
if (application == null)
{
System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
} application.AlertBeforeOverwriting = false;
application.AskToUpdateLinks = false;
application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
application.DisplayAlerts = false; workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
true, missing, missing, missing, missing, missing, missing, missing, missing);
workBook.CheckCompatibility = false;//兼容性检查
workBook.DoNotPromptForConvert = true; wSheet = (Worksheet)workBook.Worksheets[1];
return ((Microsoft.Office.Interop.Excel.Range)wSheet.Cells[row, column]).Text.ToString().Trim();
}
catch (Exception e)
{
System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。 " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
return "";
}
finally
{
if (workBook != null)
{
workBook.Close(true, missing, missing);
workBook = null;
}
if (application != null)
{
application.Quit();
KillSpecialExcel(application);
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
} /// <summary>
/// 得到当前程序的路径
/// </summary>
/// <returns></returns>
static public string GetCurrentPath()
{
string asstring = Assembly.GetExecutingAssembly().Location;
string[] aa = asstring.Split('\\');
string path = string.Empty;
foreach (string var in aa)
{
if (var != aa[aa.Length - 1])
path += var + @"\";
}
return path;
}
}
}
C#实现对EXCEL指定单元格进行操作的更多相关文章
- 使用VBA将Excel指定单元格数据、字符串或者图表对象插入到Word模板指定书签处
准备工作: 1.首先需要提供一个word模板,并且标记好您要插入书签的位置,定义书签的命名.如图 2.模拟您要插入的Excel原始数据和图表对象 插入代码如下: Private Sub Command ...
- C#修改 Excel指定单元格的值
/// <summary> /// 将指定字符串写入指定单元格中 /// </summary> /// <param name="data">要 ...
- ASP.NET 导出gridview中的数据到Excel表中,并对指定单元格换行操作
1. 使用NPOI读取及生成excel表. (1)导出Click事件: 获取DataTable; 给文件加文件名: string xlsxName = "xxx_" + DateT ...
- c#在Excel指定单元格中插入图片
方法一: /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度./// 注意:图片必须是绝对物理路径/// </summary>/// <param name="R ...
- NPOI插入图片到excel指定单元格
先看效果图 下载NPOI组件(2.0以上支持.xlsx和.xls的excel,2.0以下只支持.xls) NPOI下载官网http://npoi.codeplex.com 下载解压,里面有个dotne ...
- C# 插入条码到Excel指定单元格
.NET中Barcode Library的应用二 介绍 在上一篇中我已经简单介绍了这个函数库(条形码应用之一------------函数库的简介).在这一篇中我将使用这个库提供更多的操作,希望对大家有 ...
- excel 截取单元格部分内容(从指定位置截取)
excel 截取单元格部分内容(从指定位置截取) CreateTime--2018年5月28日08:28:46 Author:Marydon 1.情景展示 截取手机号后6位 2.实现 语法说明:r ...
- excel判断单元格包含指定内容的函数用=IF(COUNTIF(A1,"*内容*"),"0","1")
前面我们聊过怎样将Excel包含某字符的单元格填充颜色,这边我们用另外一种方法来实现:excel判断单元格包含指定内容的函数 选中需要显示结果的单元格,假设我们要判断第一行第一列的单元格A1是否含有“ ...
- vba打开excel文件遍历sheet的名字和指定单元格的值
今天项目上有个应用,获取指定Excel文件下的所有sheet的名称以及当前sheet中指定单元格的值,并把他们写到固定的sheet中去,看了下,文件比较多,而且每个文件sheet的个数比较多,也不一样 ...
随机推荐
- js检测对象属性
In:(检测自身及原型属性) var o={x:1}; "x" in o; //true,自有属性存在 "y" in o; //false "toSt ...
- JavaScript跳转和打开新窗口
跳转: window.location.href = "www.baidu.com" // 跳转到百度首页,不打开新的浏览器窗口 等价于html中的<a href=&quo ...
- Docker Compose实例
采用java -jar启动 nohup java -jar web--SNAPSHOT.jar --spring.profiles.active=test --server.port= & 采 ...
- [nowCoder] 两个长度相同有序数组的中位数
给定两个有序数组arr1和arr2,两个数组长度都为N,求两个数组中所有数的上中位数.例如:arr1 = {1,2,3,4};arr2 = {3,4,5,6};一共8个数则上中位数是第4个数,所以返回 ...
- 使用SwingWorker为界面执行异步任务
------------------siwuxie095 工程名:TestSwingWorker 包名:com.siwuxie095.swing ...
- xgene:疾病相关基因,耳聋,彩色,老年痴呆,帕金森
神经元的传递:一个下游神经元,它接受其上游神经元的各个突触传过来的信号,然而,每个突触对该下游神经元的激活权重是不同的. 从神经网络的本质上说,当人连续.多次遭受失败的时候,大脑内就会释放大量的抑制性 ...
- 17、GATK使用简介 Part2/2
转载:http://blog.sina.com.cn/s/blog_6721167201018jik.html Change Logs: 13/01/12: 增加了一篇文献,外加一些无聊的修改.12/ ...
- geneid/genesymbol/ensemblid等之间的转换
在基因注释时,难免碰到各种GENE在不同数据库之间的ID转换(例如,Ensembl ID 转Entrez ID,或者Entrez ID与GENE Symbol之间的转换).这里介绍一下常用的三个在线网 ...
- AT指令集
通用指令 at+cala 设置警报日期和时间 at+cgmi 厂家认证请求,返回模块厂家信 at+cgmm 模式认证请求,返回模块使用频段 at+cgmr 修正认证请求,返回软件版本 at+cg ...
- C#文件监控工具(对追加内容的监控并输出)
C#文件监控(对追加内容的监控并输出),适合监控某个目录下的日志文件(log),开发初衷是linux上部署在jexus部署网站后想实时输出jexus的log和自己站点的log文件(已经测试通过在mon ...