-
C# Winform环境下操作EXCEL文件的高效源代码
资源介绍
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);
}
}