c#Winform窗體 自動生成EXCEL並可以插入數據



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

using System.Windows.Forms;

using System.Data.OleDb;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Text;

namespace EPAS.f06PreData//自己命名
{
public partial class frmSetThreshold : Form
{
public frmSetThreshold()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//按鈕一進行動態創建excel
{
try
{
if (File.Exists("E:\\example.xls"))
File.Delete("E:\\example.xls");
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=example.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("CREATE TABLE booksheet1 ([測項ID] varchar, [名字] varchar,[最大閾值] varchar,[最小閾值] varchar,[備注] varchar )", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("創建excle成功");
}
}
catch (System.Exception )
{
MessageBox.Show("閾值.xls已存在!");
}
}
private void button2_Click(object sender, EventArgs e)//按鈕二點擊插入數據
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "")
{
MessageBox.Show("輸入值不能為空!");
}
else
{
string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=example.xls;Extended Properties='Excel 8.0;HDR=Yes'";//HDR=Yes表示第一行作為標題使用
OleDbConnection conn = new OleDbConnection(connstring);
string commandstring = "SELECT * FROM [booksheet1]";
OleDbDataAdapter adapter = new OleDbDataAdapter(commandstring, conn);
OleDbCommandBuilder cd = new OleDbCommandBuilder(adapter);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, "ww");
DataRow new_row1 = ds.Tables["ww"].NewRow();
new_row1["測項ID"] = textBox1.Text;
new_row1["名字"] = textBox2.Text;
new_row1["最大閾值"] = textBox3.Text;
new_row1["最小閾值"] = textBox4.Text;
new_row1["備注"] = textBox5.Text;

ds.Tables["ww"].Rows.Add(new_row1);

adapter.Update(ds, "ww");
conn.Close();
MessageBox.Show("成功導入EXCEL!");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}


}
}

 

//這趟封閉開發2017-2-16至2017-2-24  我寫代碼的能力一般,此次c#對winform窗體的控制多引用他人代碼並加以修改。

引用窗體的圖下次補上  沒有來得及附圖...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM