C#实现对EXCEL指定单元格进行操作

Posted Welcome to the Blog of Acamy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#实现对EXCEL指定单元格进行操作相关的知识,希望对你有一定的参考价值。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. //先添加引用
  5. using Microsoft.Office.Interop.Excel;
  6. using System.IO;
  7. using System.Reflection;
  8.  
  9. namespace SighExcel
  10. {
  11.     public class Sign
  12.     {
  13.         /// <summary>
  14.         /// 对Excel指定单元格进行操作
  15.         /// </summary>
  16.         /// <param name="filePath">EXCEL表格所′在路径</param>
  17.         /// <param name="row">行号</param>
  18.         /// <param name="column">列号</param>
  19.         /// <param name="code">内容</param>
  20.         /// <returns></returns>
  21.         public bool signExcel(string filePath,int row, int column,string code)
  22.         {
  23.             try
  24.             {
  25.                 _Application excelApp = new Application();
  26.                 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);
  27.                 Worksheet wSheet = (Worksheet)wBook.Worksheets[1];
  28.                 wSheet.Cells[row, column] = code;
  29.                 Microsoft.Office.Interop.Excel.Range rtemp = wSheet.Range[wSheet.Cells[3, 4], wSheet.Cells[3, 6]];
  30.                 rtemp.Font.Name="宋体";
  31.                 rtemp.Font.Size=12;
  32.                 object SaveChanges = XlSaveAction.xlDoNotSaveChanges;
  33.                 wBook.Save();
  34.                 wBook.Close();
  35.                 excelApp.Quit();
  36.                 return true;
  37.             }
  38.             catch (Exception e)
  39.             {
  40.                 System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败!错误:" + e.Message.ToString() + "" + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
  41.                 return false;
  42.             }
  43.         }
  44.         /// <summary>
  45.         ///得到当前程序的路径
  46.         /// </summary>
  47.         /// <returns></returns>
  48.         static public string GetCurrentPath()
  49.         {
  50.             string asstring = Assembly.GetExecutingAssembly().Location;
  51.             string[] aa = asstring.Split(‘\\‘);
  52.             string path = string.Empty;
  53.             foreach (string var in aa)
  54.             {
  55.                 if (var != aa[aa.Length - 1])
  56.                     path += var + @"\";
  57.             }
  58.             return path;
  59.         }
  60.     }
  61. }

以上是关于C#实现对EXCEL指定单元格进行操作的主要内容,如果未能解决你的问题,请参考以下文章

c#单元格录入时,显示过滤的数据

table里面放input去掉线

表格中如何提取指定单元格的内容呢?

Python 技术篇 - 操作excel实现单元格合并并居中实例演示,用openpyxl库为指定区域的单元格设置对齐样式和字体样式方法

C#操作Excel的技巧与方法 设置单元格等

在excel的指定单元格中输入数据