首页 > 代码库 > C#实现对EXCEL指定单元格进行操作

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指定单元格进行操作