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

使用文档

一、增、改、查、删

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. 高效率、简洁、CSS代码优化原则

    高效率.简洁.CSS代码优化原则 CSS学起来并不难,但在大型项目中,一个团队中不同的人在书写CSS风格上也有不同这样这个项目就变得难以管理,团队上就更加难以沟通,为此总结了一些如何实现高效整洁的CS ...

  2. 关于微服务、SOA、以及API的理解

    现在微服务.SOA.RESTful API设计等在各大公司很流行.微服务(micro services)这个概念不是新概念,很多公司已经在实践了,例如亚马逊.Google.FaceBook,Aliba ...

  3. 微软BI 之SSRS 系列 - 如何实现报表导航 Navigation 和钻取 Drill Down 的效果

    开篇介绍 如何在 SSRS 报表中实现标签导航 Navigation 和向下钻取 Drill Down的效果? 如同下面这个例子一样 - 在页面第一次加载的时候,默认显示是全部地区的销售总和情况,上面 ...

  4. 第八周(3) Word2007样式

    第八周(3) Word2007样式 教学时间 2013-4-19 教学课时 2 教案序号 23 教学目标 1.掌握样式的概念2.能够熟练地创建样式.修改样式的格式,使用样式3.熟练利用样式格式化文档 ...

  5. Mysql官方文档中争对安全添加列的处理方法。Mysql Add a Column to a table if not exists

    Add a Column to a table if not exists MySQL allows you to create a table if it does not exist, but d ...

  6. Nginx 访问日志分析

    0:Nginx日志格式配置 # vim nginx.conf ## # Logging Settings ## log_format access '$remote_addr - $remote_us ...

  7. gradle 配置及设置本地仓库

    安装Gradle 从官方网站下载安装包,解压到目录 设置环境变量 GRADLE_HOME=D:\gradle\gradle-3.4.1 PATH=;%GRADLE_HOME%\bin 设置本地仓库目录 ...

  8. MySQL 简单存储过程实现Redis的INCR功能

    USE test; DROP PROCEDURE IF EXISTS pro_testincrement; DELIMITER && CREATE PROCEDURE pro_test ...

  9. 【Zookeeper】源码分析之请求处理链(二)之PrepRequestProcessor

    一.前言 前面学习了请求处理链的RequestProcessor父类,接着学习PrepRequestProcessor,其通常是请求处理链的第一个处理器. 二.PrepRequestProcessor ...

  10. numpy 傅立叶得到幅值和频率

    做个备份,对 numpy 不熟,每次都找函数找半天. 代码里分几块: 1. 从 argc[1] 的文档中读取数据,并转化为 float.文档中有 2001 行,第一行为头,后面 2000 个是采样数据 ...