C#实现对EXCEL指定单元格进行操作
Posted Welcome to the Blog of Acamy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#实现对EXCEL指定单元格进行操作相关的知识,希望对你有一定的参考价值。
-
using System;
-
using System.Collections.Generic;
-
using System.Text;
-
//先添加引用
-
using Microsoft.Office.Interop.Excel;
-
using System.IO;
-
using System.Reflection;
-
-
namespace SighExcel
-
{
-
public class Sign
-
{
-
/// <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)
-
{
-
try
-
{
-
_Application excelApp = new Application();
-
Workbook wBook = excelApp.Workbooks.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
-
Worksheet wSheet = (Worksheet)wBook.Worksheets[1];
-
wSheet.Cells[row, column] = code;
-
Microsoft.Office.Interop.Excel.Range rtemp = wSheet.Range[wSheet.Cells[3, 4], wSheet.Cells[3, 6]];
-
rtemp.Font.Name="宋体";
-
rtemp.Font.Size=12;
-
object SaveChanges = XlSaveAction.xlDoNotSaveChanges;
-
wBook.Save();
-
wBook.Close();
-
excelApp.Quit();
-
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;
-
}
-
}
-
/// <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指定单元格进行操作的主要内容,如果未能解决你的问题,请参考以下文章
Python 技术篇 - 操作excel实现单元格合并并居中实例演示,用openpyxl库为指定区域的单元格设置对齐样式和字体样式方法