private void button1_Click(object sender, EventArgs e) { object path; //文件路径变量 MSExcel.Application excelApp; MSExcel.Workbook excelDoc; path = @textBox2.Text + "\\" + textBox1.Text; //路径 excelApp = new MSExcel.ApplicationClass(); //初始化 //如果已存在,则删除 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; excelDoc = excelApp.Workbooks.Add(Nothing); //使用第一个工作表作为插入数据的工作表 MSExcel.Worksheet ws = (MSExcel.Worksheet)excelDoc.Sheets[1]; //声明一个MSExcel.Range 类型的变量r MSExcel.Range r; //获得A1处的表格,并赋值 r = ws.get_Range("A1", "A1"); r.Value2 = "4.5"; //获得A2处的表格,并赋值 r = ws.get_Range("A2", "A2"); r.Value2 = "3.6"; //获得A3处的表格,并赋值 r = ws.get_Range("A3", "A3"); r.Value2 = "6.5"; //获得A4处的表格,并赋值 r = ws.get_Range("A4", "A4"); r.Value2 = "7.2"; //获得A5处的表格,并赋值 r = ws.get_Range("A5", "A5"); r.Value2 = "6.2"; excelDoc.Charts.Add(Nothing, Nothing, Nothing, Nothing); excelDoc.ActiveChart.ChartType = MSExcel.XlChartType.xlColumnClustered; excelDoc.ActiveChart.SetSourceData(ws.get_Range("A1", "A5"), MSExcel.XlRowCol.xlColumns); excelDoc.ActiveChart.Location(MSExcel.XlChartLocation.xlLocationAsObject, "sheet1"); excelDoc.ActiveChart.HasTitle = true; excelDoc.ActiveChart.ChartTitle.Text = textBox3.Text; excelDoc.ActiveChart.HasDataTable = false; //WdSaveFormat为Excel文档的保存格式 object format = MSExcel.XlFileFormat.xlWorkbookNormal; //将excelDoc文档对象的内容保存为XLSX文档 excelDoc.SaveAs(path, format, Nothing, Nothing, Nothing, Nothing, MSExcel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing); //关闭excelDoc文档对象 excelDoc.Close(Nothing, Nothing, Nothing); //关闭excelApp组件对象 excelApp.Quit(); MessageBox.Show("Excel工作簿被成功创建", "信息提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); }
C#简单操作Excel
最新推荐文章于 2019-08-10 10:39:49 发布