C# winform 读写Excel文件 实际验证通过
先引用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
namespace InfoExtraction
{
public partial class Form_Start : Form
{
public Form_Start()
{
InitializeComponent();
}
private void Form_Start_Load(object sender, EventArgs e)
{
}
private void button_run_Click(object sender, EventArgs e)
{
string currentPath = Directory.GetCurrentDirectory();
WriteExcel(currentPath + "\\results.xlsx");
MessageBox.Show("Success!");
}
private void button_exit_Click(object sender, EventArgs e)
{
Close();
Application.Exit();
}
public void WriteExcel(string filename) {
//new an excel object
Excel.Application excelApp = new Excel.ApplicationClass();
if(excelApp == null){
// if equal null means EXCEL is not installed.
MessageBox.Show("Excel is not properly installed!");
return;
}
// open a workbook,if not exist, create a new one
Excel.Workbook workBook;
if(File.Exists(filename))
{
workBook = excelApp.Workbooks.Open(filename, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
}
else
{
workBook = excelApp.Workbooks.Add(true);
}
//new a worksheet
Excel.Worksheet workSheet = workBook.ActiveSheet as Excel.Worksheet;
//write data
workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);//获得第i个sheet,准备写入
workSheet.Cells[1, 3] = "(1,3)Content";
//set visible the Excel will run in background
excelApp.Visible = false;
//set false the alerts will not display
excelApp.DisplayAlerts = false;
//workBook.SaveAs(filename, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
workBook.SaveAs(filename);
workBook.Close(false, Missing.Value, Missing.Value);
//quit and clean up objects
excelApp.Quit();
workSheet = null;
workBook = null;
excelApp = null;
GC.Collect();
}
}
}