c# +SQL+OFFICE excel出庫資料查詢及匯出
1.效果圖:
2.FORM1 SOURCE CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Web;
namespace EX_warehouse__inquire_V1._00
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
textBox1.Enabled = true;
textBox1.SelectAll();//選中文字框內容
textBox1.Focus();//指定文字框為焦點
button1.Enabled = false;
button2.Enabled = false;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
button1.Enabled = true;
button1.Focus();
}
}
private void button1_Click(object sender, EventArgs e)
{
DataBase_Inquire My_Quering = new DataBase_Inquire("NB_SERVER", "E_Panel", "sa", "adminsystem");
String StoreProcess_Str = String.Empty;
if (comboBox1.Text == "OrderNumber")
{
StoreProcess_Str = "Select * from EX_warehouse_SN_Info where OrderNumber="[email protected]"'"+textBox1.Text.Trim()[email protected]"'";
if (My_Quering.Querying_OrderNumber(StoreProcess_Str, dataGridView1, label1) == false)
MessageBox.Show("資料讀取錯誤!!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
button2.Enabled = true;
}
else if (comboBox1.Text == "BoxNumber")
{
StoreProcess_Str = "Select * from EX_warehouse_SN_Info where BoxNumber=" + @"'" + textBox1.Text.Trim() + @"'";
if (My_Quering.Querying_OrderNumber(StoreProcess_Str, dataGridView1, label1) == false)
MessageBox.Show("資料讀取錯誤!!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
button2.Enabled = true;
}
else if (comboBox1.Text == "SN")
{
StoreProcess_Str = "Select * from EX_warehouse_SN_Info where SN=" + @"'" + textBox1.Text.Trim() + @"'";
if (My_Quering.Querying_OrderNumber(StoreProcess_Str, dataGridView1, label1) == false)
MessageBox.Show("資料讀取錯誤!!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
button2.Enabled = true;
}
}
public Boolean ExportExcel_DefineTheForm(string fileName, DataGridView myDGV)//按定義的表格匯出資料
{
Boolean Flag = false;
if (myDGV.Rows.Count > 0)//存在測試資料
{
String saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel檔案|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0)
{
return true;
}
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("無法建立Excel物件,可能您的系統未安裝Excel", "系統提醒", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
//寫入標題
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
}
//寫入數值
for (int r = 0; r < myDGV.Rows.Count; r++)
{
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列寬自適應
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
Flag = true;
}
catch (Exception ex)
{
MessageBox.Show("匯出檔案時出錯,檔案可能正被開啟!\n" + ex.Message, "系統提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return false;
}
}
xlApp.Quit();
GC.Collect();//強行銷燬
MessageBox.Show("匯出檔案成功", "提示", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("報表為空,無表格需要匯出", "提示", MessageBoxButtons.OK);
return true;
}
return Flag;
}
private void button2_Click(object sender, EventArgs e)
{
String FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
ExportExcel_DefineTheForm(FileName, this.dataGridView1);
}
}
}
3.DataBase_Inquire source code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Web;
namespace EX_warehouse__inquire_V1._00
{
public class DataBase_Inquire:Form1
{
public String server;
public String database;
public String uid;
public String pwd;
//public String Stored_Procedure;
public DataBase_Inquire(String SERVER, String DATABASE, String UID, String PWD)
{
this.server = SERVER;
this.database = DATABASE;
this.uid = UID;
this.pwd = PWD;
}
public Boolean Querying_OrderNumber(String Querying_Str,DataGridView MyDgv,Label MyLab)
{
Boolean Flag = false;
String SqlConnectionStr = "server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd;
SqlConnection conn = new SqlConnection(SqlConnectionStr);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(Querying_Str,conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds,"cs");
MyDgv.DataSource = ds.Tables[0];
MyDgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
MyDgv.ReadOnly = true;
MyDgv.DefaultCellStyle.SelectionBackColor = Color.YellowGreen;
MyLab.Text = "已查詢到資料:" + (MyDgv.Rows.Count - 1).ToString() + "條";
Flag = true;
}
catch (Exception ex)
{
Flag = false;
WriteLog(ex.ToString());
}
return Flag;
}
public void WriteLog(String Str)
{
FileStream fs = new FileStream("Log.txt",FileMode.Append,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(Str);
sw.Close();
}
}
}
4.引用文的EXCEL包: