c# +SQL+OFFICE excel出库数据查询及导出

68 篇文章 1 订阅
68 篇文章 3 订阅

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="+@"'"+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 == "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包:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 C# 中的 ADO.NET 来快速导出数据Excel。下面是一个基本的示例: ```csharp using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Reflection; using Microsoft.Office.Interop.Excel; namespace ExportToExcel { class Program { static void Main(string[] args) { // 数据库连接字符串 string connectionString = "Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True"; // SQL 查询语句 string query = "SELECT * FROM MyTable"; // 创建 SQL 连接对象 using (SqlConnection connection = new SqlConnection(connectionString)) { // 打开连接 connection.Open(); // 创建 SQL 命令对象 using (SqlCommand command = new SqlCommand(query, connection)) { // 创建数据适配器对象 using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { // 创建数据集对象 DataSet dataSet = new DataSet(); // 填充数据集 adapter.Fill(dataSet); // 创建 Excel 应用程序对象 Application excel = new Application(); excel.Visible = false; excel.DisplayAlerts = false; // 创建 Excel 工作簿对象 Workbook workbook = excel.Workbooks.Add(Missing.Value); // 创建 Excel 工作表对象 Worksheet worksheet = (Worksheet)workbook.ActiveSheet; // 写入数据Excel 工作表 for (int i = 0; i < dataSet.Tables[0].Columns.Count; i++) { worksheet.Cells[1, i + 1] = dataSet.Tables[0].Columns[i].ColumnName; } for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++) { for (int j = 0; j < dataSet.Tables[0].Columns.Count; j++) { worksheet.Cells[i + 2, j + 1] = dataSet.Tables[0].Rows[i][j]; } } // 保存 Excel 文件 workbook.SaveAs("data.xlsx"); // 关闭 Excel 应用程序对象 excel.Quit(); } } } } } } ``` 在上面的代码中,我们首先定义了数据库连接字符串和 SQL 查询语句。然后,我们使用 ADO.NET 创建 SQL 连接对象、SQL 命令对象和数据适配器对象,使用数据适配器对象填充数据集。接着,我们创建 Excel 应用程序对象、Excel 工作簿对象和 Excel 工作表对象,然后将数据写入 Excel 工作表。最后,我们保存 Excel 文件并关闭 Excel 应用程序对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值