using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
public class AcessExcel
{
private Application excel = null;//excel对象
private Workbook workbook1 = null;//工作簿对象
private Worksheet worksheet1 = null;//工作表对象
//打开指定的路径的excel文件
public void openXls(string path)
{
excel = new Application();
workbook1 = excel.Workbooks.Open(path, 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);//打开工作簿
//excel.Visible = true;
}
//关闭excel文件
public void closeXls()
{
worksheet1 = null;
workbook1 = null;
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
excel = null;
System.GC.Collect();
}
//读取excel的内容
public int[,] readXls()
{
int[,] arr = new int[5,5];
int i, j;
worksheet1 = workbook1.Worksheets[1];
for (i = 2; i <= 6;i++ )
{
for (j = 2; j <= 6; j++)
{
Range range = worksheet1.Cells[i, j];
arr[i - 2, j - 2] = (int)range.Value;
}
}
return arr;
}
//写入excel表
public void writeXls(string path,int i,int[,] arr,int begin,int left)
{
openXls(path);
worksheet1 = workbook1.Worksheets[i];
Range range=worksheet1.Cells[begin,left];
range = range.get_Resize(5,5);//设置范围为5行5列
range.Value = arr;
workbook1.Save();
}
}
}
C#实现对excel单元格的存取
最新推荐文章于 2023-04-27 17:16:05 发布