如何操作Ecxel文件
private void button1_Click(object sender, System.EventArgs e)
{//保存为EXCEL文件
if(this.listView1.Items.Count<1)
return;
try
{
Excel.ApplicationClass MyExcel=new Excel.ApplicationClass();
MyExcel.Visible=true;
if(MyExcel==null)
{
MessageBox.Show("EXCEL无法启动!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
Excel.Workbooks MyWorkBooks = MyExcel.Workbooks;
Excel.Workbook MyWorkBook = MyWorkBooks.Add(Missing.Value);
Excel.Worksheet MyWorkSheet = (Excel.Worksheet)MyWorkBook.Worksheets[1];
Excel.Range MyRange = MyWorkSheet.get_Range("A1","C1");
object [] MyHeader = {"姓名","专业","毕业院校"};
MyRange.Value2= MyHeader;
if (this.listView1.Items.Count >0)
{
MyRange =MyWorkSheet.get_Range("A2",Missing.Value);
object [,] MyData = new Object[this.listView1.Items.Count,3];
foreach(ListViewItem lvi in this.listView1.Items)
{
MyData[lvi.Index,0] = lvi.Text;
MyData[lvi.Index,1] = lvi.SubItems[1].Text;
MyData[lvi.Index,2] = lvi.SubItems[2].Text;
}
MyRange = MyRange.get_Resize(this.listView1.Items.Count,3);
MyRange.Value2= MyData;
MyRange.EntireColumn.AutoFit();
}
MyExcel= null;
}
catch(Exception Err)
{
MessageBox.Show("调用EXCEL程序时出现错误!"+Err.Message,"信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
private void button2_Click(object sender, System.EventArgs e)
{//填充表格数据内容
int itemNumber=this.listView1.Items.Count;
string[] subItem0={"王斌","计算机科学技术","武汉大学"};
this.listView1.Items.Insert(itemNumber, new ListViewItem(subItem0));
string[] subItem1={"汪兰","财会电算化管理","西南财经大学"};
this.listView1.Items.Insert(itemNumber, new ListViewItem(subItem1));
string[] subItem2={"汤波","计算机软件技术","上海交通大学"};
this.listView1.Items.Insert(itemNumber, new ListViewItem(subItem2));
string[] subItem3={"罗成","计算机管理","重庆大学"};
this.listView1.Items.Insert(itemNumber, new ListViewItem(subItem3));
string[] subItem4={"汤小敏","环境保护","西南师范大学"};
this.listView1.Items.Insert(itemNumber, new ListViewItem(subItem4));
string[] subItem5={"刘功得","轻工机械装备","重庆市轻工业学校"};
this.listView1.Items.Insert(itemNumber, new ListViewItem(subItem5));
}