using Excel;
using System.Reflection;
namespace getData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//1.创建Exl应用程序对象,并显示与否.
Excel.Application xApp = new Excel.ApplicationClass();
xApp.Visible = true;
//2.创建WorkBook对象,可以有两种方式,:1.新建一个WorkBook,2.打开已有的文件.
//Workbook newBook = xApp.Workbooks.Add(Missing.Value); //新建表.
Workbook xBook = xApp.Workbooks._Open(@"d:\test.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//3.选择Sheet表,两种方式:
Worksheet tempSheet = (Excel.Worksheet)xBook.Sheets[2]; //按序表.
//Worksheet xSheet = (Excel.Worksheet)xBook.ActiveSheet; //当前表.
//读取数据,通过Range对象(通过n行n列),当单元格为空时,会报错.
Excel.Range rng1 = tempSheet.get_Range("A1", Type.Missing);
//MessageBox.Show(rng1.Value2.ToString());
//读取数据,通过Range对象,便使用不同的接口得到Range
Range rng2 = (Excel.Range)tempSheet.Cells[1, 1];
//MessageBox.Show(rng1.Value2.ToString());
//写入数据,注(好像指针一样,看着写到了变量了,但是写到了Exl表上)
for (int i = 1; i < 10; i++)
{
//Range rng3 = tempSheet.get_Range("C6", Missing.Value);
Range rng3 = (Excel.Range)tempSheet.Cells[i,i];
rng3.Value2 = "Hello";
rng3.Interior.ColorIndex = 6; //设置Range的背景色
}
//保存数据,方式一:
//xBook.SaveAs(@"d:\bookSaveAs.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value,Missing.Value);
//保存方式二:
tempSheet.SaveAs(@"d:\sheetSave.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//保存方式三
xBook.Save();
//关闭Excel应用程序
tempSheet = null;
xApp.Quit(); //这句话非常重要,否则Exlcel对象不能从内存中退出.
xApp = null;
}
}
}