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 Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace WinformWriteToExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnWriteToExcel_Click(object sender, EventArgs e)
{
Excel.Application xapp = new Excel.Application();
string filepath = @"D:\template.xlsx";
Excel.Workbook xbook = xapp.Workbooks._Open(filepath, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Excel.Worksheet xsheet = (Excel.Worksheet)xbook.Sheets[1];
Excel.Range rng = xsheet.get_Range("F1", Missing.Value);
rng.Value2 = "allen(test)";
Excel.Range rng2 = xsheet.get_Range("A4", Missing.Value);
rng2.Value2 = "10";
Excel.Range rng3 = xsheet.get_Range("B4", Missing.Value);
rng3.Value2 = "20";
Excel.Range rng4 = xsheet.get_Range("C4", Missing.Value);
rng4.Value2 = "30";
Excel.Range rng5 = xsheet.get_Range("D4", Missing.Value);
rng5.Value2 = "40";
Excel.Range rng6 = xsheet.get_Range("E4", Missing.Value);
rng6.Value2 = "50";
Excel.Range rng7 = xsheet.get_Range("F4", Missing.Value);
rng7.Value2 = "60";
Excel.Range rng8 = xsheet.get_Range("G4", Missing.Value);
rng8.Value2 = "70";
Excel.Range rng9 = xsheet.get_Range("H4", Missing.Value);
rng9.Value2 = "80";
Excel.Range rng10 = xsheet.get_Range("I4", Missing.Value);
rng10.Value2 = "90";
Excel.Range rng11 = xsheet.get_Range("A5", Missing.Value);
rng11.Value2 = DateTime.Now.ToLocalTime().ToString("yyyy-MM--dd HH:mm");
xbook.SaveAs(@"C:\test.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
MessageBox.Show("Write Success");
}
}
}