C# 操作excel

参考来源http://blog.csdn.net/dream_follower/article/details/70339849

1.添加引用 Microsoft.Office.Interop.Excel 15.0.0.0版本

2.添加声明

using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.Diagnostics;

//读取  (只读)

//取得指定或活动工作簿中所有表单的集合。只读
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
_Workbook _wbk = app.Workbooks.Add(@"C:\Users\Desktop\123.xlsx");
Sheets shs = _wbk.Sheets;                                   
_Worksheet _wsh = (_Worksheet)shs.get_Item(1);              //获取下标工作表句柄
int rowsint = _wsh.UsedRange.Cells.Rows.Count;              //得到行数
int columnsint = _wsh.UsedRange.Cells.Columns.Count;        //得到列数
Range r = _wsh.Range[_wsh.Cells[1, 1], _wsh.Cells[2, 2]];   //获取单元格范围
string gdas34 = r.Value2[1,1];                              //获取内部值

//写入  (读写)

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
object missing = System.Reflection.Missing.Value;
//创建Excel对象
Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(@"C:\Users\Desktop\123.xlsx", missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);
//取得工作薄内第一个工作表
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1);
ws.Cells[4, 7] = "4213";		 //单元格赋值
ws.get_Range("C7", "D8").Value = r.Value;//范围粘贴赋值

wb.Save();
excelApp.Quit();
wb = null;
ws = null;
excelApp = null;
Process[] procs = Process.GetProcessesByName("excel");


foreach (Process pro in procs)
{
    pro.Kill();//没有更好的方法,只有杀掉进程
}
GC.Collect();


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值