using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;

namespace WmsClient
{
    public class ExcelHelper
    {
        //Excel導入DataSet
        public static DataSet ExcelToDataSet()
        {
            DataSet dataSet = new DataSet();
            OpenFileDialog OFD = new OpenFileDialog();
            OFD.Filter = "Excel Files(.xls)|*.xls|All Files(*.*)|*.*";
            if (OFD.ShowDialog() == DialogResult.OK)
            {
                string strFileName = OFD.FileName;
                dataSet = ExcelToDataSet(strFileName);
            }
            return dataSet;
        }
        //Excel導入DataSet
        public static DataSet ExcelToDataSet(string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException("文件不存在");
            bool isExcel2003 = filePath.EndsWith(".xls");
            string connectionString = string.Format(
                isExcel2003
                ? "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;"
                : "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES\"",
                filePath);
            DataSet ds = new DataSet();
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                ][].ToString().Trim(); ;
                string commandText = "SELECT  * FROM [" + sheetName + "]";
                using (OleDbDataAdapter da = new OleDbDataAdapter(commandText, connection))
                {
                    da.Fill(ds);
                    connection.Close();
                }
            }
            return ds;
        }
        //DataGridView導出Excel
        public static void DataGridViewToExcel(DataGridView dgv)
        {
            //DataTableToExcel(dgv.DataSource as DataTable);//數據源為DataTable時適用

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.FilterIndex = ;
            dlg.RestoreDirectory = true;
            dlg.Title = "保存為Excel文件";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.Default);
                string columnTitle = "";
                try
                {
                    //寫入標題列
                    ; i < dgv.ColumnCount; i++)
                    {
                        if (dgv.Columns[i].Visible)
                        {
                            if (columnTitle == "")
                            {
                                columnTitle = "\"" + dgv.Columns[i].HeaderText + "\"";
                            }
                            else
                            {
                                columnTitle += "\t" + "\"" + dgv.Columns[i].HeaderText + "\"";
                            }
                        }
                    }
                    sw.WriteLine(columnTitle);

                    //寫入內容列
                    ; j < dgv.Rows.Count; j++)
                    {
                        string columnValue = "";
                        ; i < dgv.Columns.Count; i++)
                        {
                            if (dgv.Columns[i].Visible)
                            {
                                string cellValue = dgv.Rows[j].Cells[i].Value == null ? "" : dgv.Rows[j].Cells[i].FormattedValue.ToString().Replace("\"", "'");
                                if (columnValue == "")
                                {
                                    columnValue = "\"" + cellValue + "\"";
                                }
                                else
                                {
                                    columnValue += "\t" + "\"" + cellValue + "\"";
                                }
                            }
                        }
                        sw.WriteLine(columnValue);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
        //DataTable導出Excel
        public static void DataTableToExcel(DataTable table)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.FilterIndex = ;
            dlg.RestoreDirectory = true;
            dlg.Title = "保存為Excel文件";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.Default);
                string columnTitle = "";
                try
                {
                    //寫入標題列
                    ; i < table.Columns.Count; i++)
                    {
                        if (columnTitle == "")
                        {
                            columnTitle = "\"" + table.Columns[i].ColumnName + "\"";
                        }
                        else
                        {
                            columnTitle += "\t" + "\"" + table.Columns[i].ColumnName + "\"";
                        }
                    }
                    sw.WriteLine(columnTitle);

                    //寫入內容列
                    ; j < table.Rows.Count; j++)
                    {
                        string columnValue = "";
                        ; i < table.Columns.Count; i++)
                        {
                            string cellValue = table.Rows[j][i] == DBNull.Value ? "" : table.Rows[j][i].ToString().Replace("\"", "'");
                            if (columnValue == "")
                            {
                                columnValue = "\"" + cellValue + "\"";
                            }
                            else
                            {
                                columnValue += "\t" + "\"" + cellValue + "\"";
                            }
                        }
                        sw.WriteLine(columnValue);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
    }
}
 

C#在Excel的簡單操作--適用:與DB數據的簡單交互的更多相关文章

  1. 使用DataSet與DataAdapter對數據庫進行操作

    1.定義連接字符串 var source = "server=(local); integrated security=SSPI; database=test"; var conn ...

  2. c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出

    c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...

  3. 无法将类型为“Excel.ApplicationClass”的 COM 对象强制转换为接口类 型“Excel._Application”。此操作失败的原因是对 IID 为“{000208D5 -0000-0000-C000-000000000046}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 加载类型库/DLL 时出错。 (异常来 自 HRESULT:

    无法将类型为“Excel.ApplicationClass”的 COM 对象强制转换为接口类 型“Excel._Application”.此操作失败的原因是对 IID 为“{000208D5 -000 ...

  4. VBA基础之Excel VBA 表格的操作(一)

    一.Excel VBA 表格的操作1. Excel表格的指定以及表格属性的设置 Sub main() '把表格B2的值改为"VBA Range和Cells函数" Range(&qu ...

  5. Excel怎么增加撤销操作的次数?Excel增加可撤销次数教程

    Excel怎么增加撤销操作的次数?Excel增加可撤销次数教程 在Excel的使用中,返回上一步是经常用到的一个工具,当数据填写有误需要查看之前的内容时,一般会通过"Ctrl Z" ...

  6. python读取数据写入excel的四种操作

    Python对Excel的读写主要有:xlrd.xlwt.xlutils.openpyxl.xlsxwriter几种 xlutils结合xlrd: 操作的是以xls后缀的excel,读取文件保留原格式 ...

  7. python学习笔记(十三)-python对Excel进行读写修改操作

    日常工作中会遇到Excel的读写问题.我们可以使用xlwt 模块将数据写入Excel表格,使用xlrd 模块从Excel读取数据,使用xlutils模块和xlrd模块结合对Excel数据进行修改.下面 ...

  8. PHPExcel讀取excel數據

    require_once 'PHPExcel.php'; $PHPReader = new PHPExcel_Reader_Excel2007(); $filePath = 'wjyl.xlsx'; ...

  9. gcc 簡單操作

    gcc -c test.c 產出 test.o object file gcc -c test.c -o XXX 產出 XXX object file gcc test.c -o aaa 產出 aaa ...

随机推荐

  1. 关于mysqld_safe

    昨天花了一天时间写了mysql的源码安装,比较蛋疼.其中对于mysqld_safe尤其不理解,因为使用apt-get安装几乎中间不需要什么配置,只需要service mysql start即可,但是源 ...

  2. apple IOS的base64编解码

    <pre style="word-wrap: break-word; white-space: pre-wrap;">/* * Copyright (c) 2003 A ...

  3. 并不对劲的p3709:大爷的字符串题

    题目大意 区间众数 题解 莫队 代码 #include<algorithm> #include<cmath> #include<cstdio> #include&l ...

  4. Ubuntu下搭建基于apache2的gerrit+gitweb服务器

    说明:Ubuntu版本12.04 1. 配置gerrit管理帐号 1 sudo adduser gerrit 增加sudo权限: 1 sudo usermod -a -G sudo gerrit 切换 ...

  5. Cortex-M3 / M4 Hard Fault Handler (转载)

    转自大伟的,感谢大伟的帮助调试:http://www.cnblogs.com/shangdawei/archive/2013/04/30/3052491.html http://blog.frankv ...

  6. 常见电商项目的数据库表设计(MySQL版)

    转自:https://cloud.tencent.com/developer/article/1164332 简介: 目的: 电商常用功能模块的数据库设计 常见问题的数据库解决方案 环境: MySQL ...

  7. Ruby module里的self

    创建: 2018/03/15 更新: 2018/03/22 把标题ruby首字母大写 都知道def self.方法名 来定义类方法 class SampleClass def self.class_m ...

  8. mui 每次页面跳转用mui.openWindow会不会占用很大内存?

    http://ask.dcloud.net.cn/question/5384 不能每次用mui.openWindow.不用的webview要close,一个webview被close后会露出其他没有被 ...

  9. TCP模型,控制标志,握手,挥手,长连接*

    1. TCP协议 Transmission Control Protocol,传输控制协议 面向连接的协议 需要三次握手建立连接 需要四次挥手断开连接 TCP报头最小长度:20字节 2.模型图 3.T ...

  10. .NET通过字典给类赋值

    /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam& ...