昨天帮朋友做了个小工具,以完成多表连接处理一些数据。今天下班后又做了份使用文档,不知友能看懂否?现将使用文档及源码发布如下,以供有同样需求的朋友下载。

使用文档

一、增、改、查、删

1、增(向sheet中插入数据):

INSERT INTO [Employee$](EmployeeId,EmployeeName,BranchId) VALUES('YG2014120001','韩兆新','BM20141201');

执行Sql前:

执行Sql后:

2、改(更新sheet中的数据):

UPDATE [Employee$] SET BranchId = 'BM20141202';

执行Sql前:

执行Sql后:

3、查(在sheet中查询数据):

SELECT EmployeeId,EmployeeName,BranchId FROM [Employee$];

4、删(从sheet中删除数据):

显然不支持!

二、WHERE:(WHERE在修改、查询中的应用)

1、修改:

UPDATE [Employee$] SET EmployeeID=null,EmployeeName=null,BranchId=null WHERE EmployeeID='YG2014120003';

执行Sql前:

执行Sql后:

2、查询:

SELECT EmployeeId,EmployeeName,BranchId FROM [Employee$] WHERE EmployeeID = 'YG2014120002';

三、LIKE与通配符

SELECT * FROM [Employee$] WHERE EmployeeID LIKE 'YG201412%';

1、*:所有列的名称;

2、%:通配n个字符;

3、_:通配1个字符。

四、排序(ORDER BY)

1、升序:(ASC)可省略;

2、降序:(DSEC)。

示例1:(升序排序)

SELECT * FROM [Employee$] ORDER BY EmployeeId DESC;

示例2:(降序排序)

SELECT * FROM [Employee$] ORDER BY EmployeeId DESC;

示例3:(升序排序简写)

SELECT * FROM [Employee$] ORDER BY EmployeeId;

五、多sheet连接

先建立两个用于演示的sheet:

Characters:

ID Character
1 内向
2 外向
3 中性性格

Colors:

ID Color
1 绿色
2 红色
4 蓝色

1、内连接:

内连接(JOIN  或 INNER JOIN):内连接取交集

示意图:

SELECT * FROM [characters$] INNER JOIN [colors$] ON [characters$].ID = [colors$].ID;

2、外连接:

外连接可分为:左连接、右连接、完全外连接。

(1)左连接(LEFT JOIN):

示意图:

SELECT * FROM [characters$] LEFT JOIN [colors$] ON [characters$].ID = [colors$].ID;

结果:

(2)右连接(RIGHT JOIN):

示意图:

SELECT * FROM [characters$] RIGHT JOIN [colors$] ON [characters$].ID = [colors$].ID;

结果:

(3)完全外连接:

示意图:

SELECT * FROM [characters$] LEFT JOIN [colors$] ON [characters$].ID = [colors$].ID

UNION

SELECT * FROM [characters$] RIGHT JOIN [colors$] ON [characters$].ID = [colors$].ID;

结果:

3、交叉连接( CROSS JOIN ):

交叉连接产生连接所涉及的表的笛卡尔积。

SELECT * FROM [characters$],[colors$];

结果:


4、补充:

1、如下可获取内连接结果:

SELECT * FROM [characters$],[colors$] WHERE [characters$].ID = [colors$].ID;

2、如下可获取交叉连接结果:

SELECT * FROM [characters$],[colors$];


源码:

Program.cs

using System;

using System.IO;

using System.Windows.Forms;

 

namespace SqlExcel

{

    static class Program

    {

        /// <summary>

        /// 应用程序的主入口点。

        /// </summary>

        [STAThread]

        static void Main()

        {

            Sunisoft.IrisSkin.SkinEngine skinEngine = new Sunisoft.IrisSkin.SkinEngine();

            string skinPath = Application.StartupPath + Path.DirectorySeparatorChar + "skin" + Path.DirectorySeparatorChar + "skin.ssk";

            skinEngine.SkinFile = skinPath;

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new MainForm());

        }

    }

}

MainForm.cs

using System;

using System.Data;

using System.Data.Common;

using System.Drawing;

using System.Windows.Forms;

 

namespace SqlExcel

{

    public partial class MainForm : Form

    {

        public MainForm()

        {

            InitializeComponent();

        }

        /// <summary>

        /// 输入文件选择

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnInFile_Click(object sender, EventArgs e)

        {

            OpenFileDialog openFileDlg = new OpenFileDialog();

            openFileDlg.Filter = "Excel 2003文件|*.xls|Excel 2007文件|*.xlsx";

            if (DialogResult.OK.Equals(openFileDlg.ShowDialog()))

            {

                txtInFile.Text = openFileDlg.FileName;

            }

 

        }

        /// <summary>

        /// 执行Sql...

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnExecute_Click(object sender, EventArgs e)

        {

            if (string.IsNullOrEmpty(txtInFile.Text.Trim()))

            {

                MessageBox.Show("请选择输入文件!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

            if (string.IsNullOrEmpty(txtSql.Text.Trim()))

            {

                MessageBox.Show("请输入Sql语句!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

            int linesNum = 0;

            double executionTime = 0.0;

            string resultInfo = string.Empty;

            DataTable dtResult = null;

            tabResult.SelectedTab = tPageResultInfo;

            try

            {

                if (txtSql.Text.ToLower().StartsWith("select"))

                {

                    executionTime = CodeTimer.ExecuteCode(delegate()

                    {

                        dtResult = SqlHelper.ExecuteDataTable(txtInFile.Text, txtSql.Text);

                    });

                    tabResult.SelectedTab = tPageResult;

                }

                else

                {

                    executionTime = CodeTimer.ExecuteCode(delegate()

                    {

                        linesNum = SqlHelper.ExecuteNonQuery(txtInFile.Text, txtSql.Text);

                    });

                }

                resultInfo = FormatResultInfo(txtSql.Text, linesNum, executionTime);

            }

            catch (Exception ex)

            {

                if (ex.Message.Equals("未在本地计算机上注册“Microsoft.Ace.OLEDB.12.0”提供程序。"))

                {

                    MessageBox.Show("本程序运行需安装:AccessDatabaseEngine,\r\n请安装后重试!", "系统警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }

                else if (ex is DbException)

                {

                    MessageBox.Show(string.Format("Sql语句错误:“{0}”", ex.Message), "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                else

                {

                    MessageBox.Show(string.Format("发生未处理错误,请联系作者!\r\n错误信息:“{0}”", ex.Message), "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

                resultInfo = FormatResultInfo(txtSql.Text, ex.Message);

            }

            finally

            {

                gvResult.DataSource = dtResult;

                txtResultInfo.Text = resultInfo;

            }

        }

        /// <summary>

        /// 到处结果数据

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnExport_Click(object sender, EventArgs e)

        {

            DataTable dt = gvResult.DataSource as DataTable;

            if (null == dt)

            {

                MessageBox.Show("无操作结果!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

            SaveFileDialog saveFileDlg = new SaveFileDialog();

            saveFileDlg.Filter = "Excel 2003文件|*.xls|Excel 2007文件|*.xlsx";

            if (DialogResult.OK.Equals(saveFileDlg.ShowDialog()))

            {

                try

                {

                    ExcelHelper.DataTableToExcel(dt, "result", saveFileDlg.FileName);

                    MessageBox.Show("导出成功", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.None);

                }

                catch (Exception ex)

                {

                    MessageBox.Show(string.Format("导出失败,原因:“{0}”", ex.Message), "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }

        }

 

        //显示行号

        private void gvResult_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

        {

            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,

                e.RowBounds.Location.Y,

                gvResult.RowHeadersWidth - 4,

                e.RowBounds.Height);

 

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),

                gvResult.RowHeadersDefaultCellStyle.Font,

                rectangle,

                gvResult.RowHeadersDefaultCellStyle.ForeColor,

                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

        }

 

        #region 格式化Sql执行结果信息

        private string FormatResultInfo(string sql, int linesNum, double executionTime)

        {

            return string.Format("[SQL]{0}\r\n受影响的行: {1}\r\n时间: {2}ms\r\n", sql, linesNum, executionTime);

        }

        private string FormatResultInfo(string sql, string errorInfo)

        {

            return string.Format("[SQL]{0}\r\n[Err]{1}", sql, errorInfo);

        }

        #endregion

    }

}

SqlHelper.cs

using System;

using System.Configuration;

using System.Data;

using System.Data.OleDb;

 

namespace SqlExcel

{

    static class SqlHelper

    {

        private static string GetConnectionString(string dataSource)

        {

            if (string.IsNullOrEmpty(dataSource))

            {

                throw new Exception("数据源不能为空!");

            }

            return string.Format(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString, dataSource);

        }

        public static DataTable ExecuteDataTable(string dataSource, string sql, params OleDbParameter[] parameters)

        {

            using (OleDbConnection conn = new OleDbConnection(GetConnectionString(dataSource)))

            {

                using (OleDbCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = sql;

                    cmd.Parameters.AddRange(parameters);

                    using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))

                    {

                        DataTable dt = new DataTable();

                        da.Fill(dt);

                        return dt;

                    }

                }

            }

        }

 

        public static int ExecuteNonQuery(string dataSource, string sql, params OleDbParameter[] parameters)

        {

            using (OleDbConnection conn = new OleDbConnection(GetConnectionString(dataSource)))

            {

                conn.Open();

                using (OleDbCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = sql;

                    cmd.Parameters.AddRange(parameters);

                    return cmd.ExecuteNonQuery();

                }

            }

        }

    }

}

ExcelHelper.cs

using System;

using System.Data;

using System.IO;

using NPOI.HSSF.UserModel;

using NPOI.SS.UserModel;

using NPOI.XSSF.UserModel;

 

namespace SqlExcel

{

    static class ExcelHelper

    {

        #region 导出DataTable到Excel(Author:hanzhaoxin/2014-12-12)

 

        public static void DataTableToExcel(DataTable dtSource, string sheetName, string fileName)

        {

            string extension = Path.GetExtension(fileName);

            IWorkbook workbook;

            if (extension.Equals(".xls"))

            {

                workbook = new HSSFWorkbook();

            }

            else if (extension.Equals(".xlsx"))

            {

                workbook = new XSSFWorkbook();

            }

            else

            {

                throw new Exception("不是有效的Excel格式!");

            }

            ISheet sheet = workbook.CreateSheet(sheetName);

            IRow headerRow = sheet.CreateRow(0);

            foreach (DataColumn cl in dtSource.Columns)

            {

                headerRow.CreateCell(cl.Ordinal).SetCellValue(cl.ColumnName);

            }

            int rowIndex = 1;

            foreach (DataRow dr in dtSource.Rows)

            {

                IRow dataRow = sheet.CreateRow(rowIndex);

                foreach (DataColumn cl in dtSource.Columns)

                {

                    #region SetCellValue

                    switch (cl.DataType.ToString())

                    {

                        case "System.String":

                            dataRow.CreateCell(cl.Ordinal).SetCellValue(dr[cl].ToString());

                            break;

                        case "System.DateTime":

                            DateTime dtCellValue = new DateTime();

                            DateTime.TryParse(dr[cl].ToString(), out dtCellValue);

                            dataRow.CreateCell(cl.Ordinal).SetCellValue(dtCellValue);

                            break;

                        case "System.Boolean":

                            bool blCellValue;

                            bool.TryParse(dr[cl].ToString(), out blCellValue);

                            dataRow.CreateCell(cl.Ordinal).SetCellValue(blCellValue);

                            break;

                        case "System.Int16":

                        case "System.Int32":

                        case "System.Int64":

                        case "System.Byte":

                            int iCellValue;

                            int.TryParse(dr[cl].ToString(), out iCellValue);

                            dataRow.CreateCell(cl.Ordinal).SetCellValue(iCellValue);

                            break;

                        case "System.Decimal":

                        case "System.Double":

                            double doubCellValue;

                            double.TryParse(dr[cl].ToString(), out doubCellValue);

                            dataRow.CreateCell(cl.Ordinal).SetCellValue(doubCellValue);

                            break;

                        case "System.DBNull":

                            dataRow.CreateCell(cl.Ordinal).SetCellValue("");

                            break;

                        default:

                            dataRow.CreateCell(cl.Ordinal).SetCellValue(dr[cl].ToString());

                            break;

                    }

                    #endregion

                }

                rowIndex++;

            }

            using (FileStream fs = File.OpenWrite(fileName))

            {

                workbook.Write(fs);

                headerRow = null;

                sheet = null;

                workbook = null;

            }

        }

        #endregion

    }

}

CodeTimer.cs

using System.Diagnostics;

 

namespace SqlExcel

{

    delegate void Action();

    static class CodeTimer

    {

        public static double ExecuteCode(Action dgMethodName)

        { 

            Stopwatch sw = new Stopwatch();

            sw.Start();

            dgMethodName.Invoke();

            sw.Stop();

            return sw.Elapsed.TotalMilliseconds;

        }

    }

}

App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <connectionStrings>

        <add name="Conn" connectionString="Provider=Microsoft.Ace.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source={0};"/>

    </connectionStrings>

</configuration>

下载

因该程序运行需注册“Microsoft.Ace.OLEDB.12.0”,考虑到很多朋友没有安装。后面也会给出下载“AccessDatabaseEngine.exe”的链接。

下载地址:

SqlExcel源码:http://files.cnblogs.com/hanzhaoxin/SqlExcel%E6%BA%90%E7%A0%81.zip

AccessDatabaseEngine:http://www.microsoft.com/zh-cn/download/details.aspx?id=13255

SqlExcel使用文档及源码的更多相关文章

  1. jQuery LigerUI 最新版压缩包(含chm帮助文档、源码、donet权限示例)

    jQuery LigerUI 最新版压缩包 http://download.csdn.net/download/heyin12345/4680593 jQuery LigerUI 最新版压缩包(含ch ...

  2. 【VB6 学习文档管理系统源码】

    VB6写的一款笔记软件的源码,里面包含有很多窗体控件的使用技巧,比如MSHFlexgrid表格.TreeView的动态加载.Ado的增删改查等. 本软件提供对日常生活.工作中的学习笔记.图文并茂存储以 ...

  3. 突发奇想之:源码及文档,文档包括源码---xml格式的源码,文档源码合并;注释文档化,文档代码化;

    目前源码和文档一般都是分开的,我在想为什么 源码不就是最好的文档么? 但是一般源码都是文本text的,格式化需要人为统一规范,所以源码中的文档在现实中不是那么的易于实践. 而且 源码 不能包括图片.附 ...

  4. Thinking in Java 4th(Java编程思想第四版)文档、源码、习题答案

    Thinking in Java 4th 中.英文两版pdf文档,书中源码及课后习题答案.链接:https://pan.baidu.com/s/1BKJdtgJ3s-_rN1OB4rpLTQ 密码:2 ...

  5. druid 文档 和 源码地址

    Druid文档 :https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98 maven仓库:http://c ...

  6. C# 30分钟完成百度人脸识别——进阶篇(文末附源码)

    距离上次入门篇时隔两个月才出这进阶篇,小编惭愧,对不住关注我的卡哇伊的小伙伴们,为此小编用这篇博来谢罪. 前面的准备工作我就不说了,注册百度账号api,创建web网站项目,引入动态链接库引入. 不了解 ...

  7. 一文了解如何源码编译Rainbond基础组件

    Rainbond 主要由以下三个项目组成,参考官网详细 技术架构 业务端 Rainbond-UI 和 Rainbond-Console 合起来构成了业务层.业务层是前后端分离模式.UI是业务层的前端代 ...

  8. 基于Socket通讯(C#)和WebSocket协议(net)编写的两种聊天功能(文末附源码下载地址)

    今天我们来盘一盘Socket通讯和WebSocket协议在即时通讯的小应用——聊天. 理论大家估计都知道得差不多了,小编也通过查阅各种资料对理论知识进行了充电,发现好多demo似懂非懂,拷贝回来又运行 ...

  9. CSDN新版Markdown编辑器(Alpha 2.0版)使用示例(文首附源码.md文件)

    CSDN新版Markdown编辑器(Alpha 2.0版) 使用示例 附 本文的Markdown源码: https://github.com/yanglr/AlgoSolutions/blob/mas ...

随机推荐

  1. js 时间加减

    //js格式化时间 "yyyy-MM-dd hh:mm:ss" Date.prototype.Format = function (fmt) { var o = { "M ...

  2. mssql批量删除数据库里所有的表

    go declare @tbname varchar(250) declare #tb cursor for select name from sysobjects where objectprope ...

  3. 查看一个目录是否已经mount --bind

    执行 mountpoint -q /test/mount echo $? 如果是0表示已经mount mountpoint -q /test/mount || mount -o bind /some/ ...

  4. 微信小程序 - template和include详细描述

    演示 index.wxml <!-- 内部模板 --> <template name="all"> {{a}} {{b}} </template> ...

  5. [译]AngularJS Services 获取后端数据

    原文:ANGULARJS SERVICES – FETCHING SERVER DATA $http是AngularJS内置的服务,能帮助我们完成从服务端获数据.简单的用法就是在你需要数据的时候,发起 ...

  6. 设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释

    模板方法模式(template method pattern) 排序(sort) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考模板方法模式(tem ...

  7. java.lang.ClassNotFoundException: SparkPi$$anonfun$1

    出现这个错误可能有两种情况,Jar文件没有传上去,或者Build Path里面包含的Jar文件和Spark的运行环境有冲突. 对于第一种情况,需要在SparkConf语句后面加上Jar文件的路径: v ...

  8. Aerospike系列:8:集群宕机演练

    1:初始的集群状态 2:关掉192.168.91.133:3000 3:再关掉192.168.91.135:3000 3:再关掉192.168.91.144:3000 5:恢复192.168.91.1 ...

  9. JqGrid把数据行插入指定位置的方法addRowData

    1.首页在colModel里写好方法,如下代码options.rowId是获取当前行的编号 { label: '操作', width: 60, align: 'center', formatter: ...

  10. LeetCode] binaryTreePaths

    class Solution { public: void binaryPath(TreeNode* root, vector<string>& result, string pa ...