using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; namespace PDM {
    public partial class Export : Form {
        public Export() {
            InitializeComponent();
            this.tbxserver.Text = "192.168.17.216";
            this.tbxserverName.Text = "mf_spare_2014_0801";
            this.tbxname.Text = "sa";
            this.tbxpassword .Text= "sunlight";
        }         private void button1_Click(object sender, EventArgs e) {
            try {
                string strsql;
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = "d:\\";
                openFileDialog.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
                openFileDialog.FilterIndex = 1;
                DataSet dss = new DataSet();
                SqlConnection oraCon = new SqlConnection(string.Format("server={0};database={1};uid={2};pwd={3}", this.tbxserver.Text, this.tbxserverName.Text,this.tbxname.Text, this.tbxpassword.Text));
                oraCon.Open();
              //  SqlConnection oraCon = new SqlConnection(string.Format("user id={0};data source={1};password={2}", this.tbxname.Text, this.tbxserver.Text, this.tbxpassword.Text));
                if(openFileDialog.ShowDialog() == DialogResult.OK) {
                    var fName = openFileDialog.FileName;
                    var importtable = XlSToDataTable(fName, "dd", 0);
                    this.dataGridView1.DataSource = importtable;
                    foreach(DataRow item in importtable.Rows) {
                        DataTable dt = new DataTable();
                        dt.TableName = item[0].ToString();
                        strsql = (item[1].ToString());
                        SqlDataAdapter oraDap = new SqlDataAdapter(strsql, oraCon);
                        oraDap.Fill(dt);
                        dss.Tables.Add(dt);
                    }
                    Stream myStream;
                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.Filter = "xls files (*.xls)|*.xls|All files (*.*)|*.*";
                    saveFileDialog1.FileName = "导出数据";
                    saveFileDialog1.FilterIndex = 1;
                    if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                        GridToExcelByNPOI(dss, saveFileDialog1.FileName);
                    }
                } oraCon.Close();
                
            } catch(Exception ex) {
                throw ex;
            }
           
        }         private static void GridToExcelByNPOI(DataSet ds, string strExcelFileName) {
            try {
                HSSFWorkbook workbook = new HSSFWorkbook();
                int i = 0;
                foreach(DataTable dt in ds.Tables) {
                    i++;
                    ISheet sheet = workbook.CreateSheet(dt.TableName);
                    //用column name 作为列名
                    int icolIndex = 0;
                    IRow headerRow = sheet.CreateRow(0);
                    foreach(DataColumn item in dt.Columns) {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(item.ColumnName);
                        icolIndex++;
                    }
                    int iRowIndex = 1;
                    int iCellIndex = 0;
                    foreach(DataRow Rowitem in dt.Rows) {
                        IRow DataRow = sheet.CreateRow(iRowIndex);
                        foreach(DataColumn Colitem in dt.Columns) {
                            ICell cell = DataRow.CreateCell(iCellIndex);
                            cell.SetCellValue(Rowitem[Colitem].ToString());
                            iCellIndex++;
                        }
                        iCellIndex = 0;
                        iRowIndex++;
                    }
                }
                FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
                workbook.Write(file);
                file.Flush();
                file.Close();
            } catch(Exception ex) {
            } finally {
                //workbook = null;
            }
        }         /// <summary>
        /// Excel文件导成Datatable
        /// </summary>
        /// <param name="strFilePath">Excel文件目录地址</param>
        /// <param name="strTableName">Datatable表名</param>
        /// <param name="iSheetIndex">Excel sheet index</param>
        /// <returns></returns>
        public static DataTable XlSToDataTable(string strFilePath, string strTableName, int iSheetIndex) {             string strExtName = Path.GetExtension(strFilePath);             DataTable dt = new DataTable();
            if(!string.IsNullOrEmpty(strTableName)) {
                dt.TableName = strTableName;
            }             if(strExtName.Equals(".xls") || strExtName.Equals(".xlsx")) {
                using(FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read)) {
                    HSSFWorkbook workbook = new HSSFWorkbook(file);
                    ISheet sheet = workbook.GetSheetAt(iSheetIndex);                     //列头
                    foreach(ICell item in sheet.GetRow(sheet.FirstRowNum).Cells) {
                        dt.Columns.Add(item.ToString(), typeof(string));
                    }                     //写入内容
                    System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                    while(rows.MoveNext()) {
                        IRow row = (HSSFRow)rows.Current;
                        if(row.RowNum == sheet.FirstRowNum) {
                            continue;
                        }                         DataRow dr = dt.NewRow();
                        foreach(ICell item in row.Cells) {
                            switch(item.CellType) {
                                case CellType.Boolean:
                                    dr[item.ColumnIndex] = item.BooleanCellValue;
                                    break;
                                case CellType.Formula:
                                    switch(item.CachedFormulaResultType) {
                                        case CellType.Boolean:
                                            dr[item.ColumnIndex] = item.BooleanCellValue;
                                            break;
                                        case CellType.Numeric:
                                            if(DateUtil.IsCellDateFormatted(item)) {
                                                dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
                                            } else {
                                                dr[item.ColumnIndex] = item.NumericCellValue;
                                            }
                                            break;
                                        case CellType.String:
                                            string str = item.StringCellValue;
                                            if(!string.IsNullOrEmpty(str)) {
                                                dr[item.ColumnIndex] = str.ToString();
                                            } else {
                                                dr[item.ColumnIndex] = null;
                                            }
                                            break;
                                        case CellType.Unknown:
                                        case CellType.Blank:
                                        default:
                                            dr[item.ColumnIndex] = string.Empty;
                                            break;
                                    }
                                    break;
                                case CellType.Numeric:
                                    if(DateUtil.IsCellDateFormatted(item)) {
                                        dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
                                    } else {
                                        dr[item.ColumnIndex] = item.NumericCellValue;
                                    }
                                    break;
                                case CellType.String:
                                    string strValue = item.StringCellValue;
                                    if(!string.IsNullOrEmpty(strValue)) {
                                        dr[item.ColumnIndex] = strValue.ToString();
                                    } else {
                                        dr[item.ColumnIndex] = null;
                                    }
                                    break;
                                case CellType.Unknown:
                                case CellType.Blank:
                                default:
                                    dr[item.ColumnIndex] = string.Empty;
                                    break;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }         private void btexport_Click(object sender, EventArgs e) {         }
    }
}

nopi导入导出的更多相关文章

  1. NOPI导入导出EXCEL

    一.简介 1. 什么是NPOI NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office 97 ...

  2. NOPI实现导入导出泛型List,支持自定义列

    概述 业务上需要自定义列的Excel的导入导出,在网上看了好多资料,很多都是有Bug而且都是支持Excel和DataTable的转换,所以自己总结了一下,应用.NET平台上的NPOI封装了支持自定义列 ...

  3. asp.net mvc4 easyui datagrid 增删改查分页 导出 先上传后导入 NPOI批量导入 导出EXCEL

    效果图 数据库代码 create database CardManage use CardManage create table CardManage ( ID ,) primary key, use ...

  4. ASP.NET Core使用EPPlus导入导出Excel

    开发过程中,经常会遇到导入导出数据的需求,本篇博客介绍在.NET Core中如何使用EPPlus组件导入导出Excel EPPlus: EPPlus是使用Open Office XML格式(xlsx) ...

  5. 企业级自定义表单引擎解决方案(十六)--Excel导入导出

    Excel对于后端管理系统来说,永远都是绕不开的话题,开发Excel导入导出功能往往都比较麻烦,因为涉及到Excel导入模板制作.Excel表格数据与系统数据库表字段映射.Excel导入数据验证.验证 ...

  6. CRL快速开发框架系列教程九(导入/导出数据)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  7. ITTC数据挖掘平台介绍(五) 数据导入导出向导和报告生成

    一. 前言 经过了一个多月的努力,软件系统又添加了不少新功能.这些功能包括非常实用的数据导入导出,对触摸进行优化的画布和画笔工具,以及对一些智能分析的报告生成模块等.进一步加强了平台系统级的功能. 马 ...

  8. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  9. Oracle 数据库导入导出 dmp文件

    转自: http://hi.baidu.com/ooofcu/blog/item/ec5d1f9580d41f007af48077.html 首先询问对方数据库的表空间名称和大小,然后在你的oracl ...

随机推荐

  1. 直接将视频文件原码流转换成YUV,输出到屏幕显示

    #include "stdafx.h" #define inline _inline#ifndef INT64_C#define INT64_C(c) (c ## LL)#defi ...

  2. wpf 自定义依赖性属性 作用之一 对数据绑定的支持

    依赖属性:定义,声明,注册 依赖属性,在数据绑定中,数据绑定,分为源对象(数据源)和目标对象(显示数据). 只有源对象为依赖对象,属性为依赖属性时,该属性才会在属性发生变化时,通知目标对象进行数据更改 ...

  3. 【HDOJ】1606 Excuses, Excuses!

    简单字符串. #include <cstdio> #include <cstring> #define MAXLEN 105 #define MAXN 25 char keys ...

  4. codeforces #268 div2 D

    对于这道题第一感觉是图论相关然后我们先分析,假设a[i]在A集合需要的元素是a[x],在B集合是a[y]那么假设a[i]在A集合,那必然a[x]也必须在A集合,由于a[y]如果在B集合就没有对应元素, ...

  5. bzoj 1923 [Sdoi2010]外星千足虫(高斯消元+bitset)

    1923: [Sdoi2010]外星千足虫 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 634  Solved: 397[Submit][Status ...

  6. Mathlab编程-微积分在Matlab中的解法

    这一章节将介绍一系列典型的微积分问题(求极限.级数.定积分.导数.重积分等)在Matlab中的求解. 首先关于极限: (1)    数列极限: 给出下面三段例程. 求解数列极限的limit函数参数说明 ...

  7. 关于数据库一致改关闭下redo日志文件丢失的处理办法的总结

    数据库一致性关闭下redo日志文件丢失的处理办法(归档和非归档都行) 1. inactive log  在一致性关闭后删除重启时可以在mount下(不丢失数据) alter database clea ...

  8. Error, some other host already uses address

    rhel 5.9,在修改完网卡配置信息重启网卡之后提示如下无法激活网卡: Error, some other host already uses address 确认配置的IP地址是没有在用的,解决办 ...

  9. Eclipse下Tomcat常用设置

    Eclipse下Tomcat常用设置 1,Eclipse建立Tomcat服务 1.1 新建Server 首先这里是指,jee版的Eclipse.Eclipse是没有像MyEclipse那样集成Tomc ...

  10. IOS开发中 RunLoop,RunTime

    1.Objective-C中的函数调用 对于C语言,函数调用是由编译器直接转化完成的,在编译时程序就开始查找要执行的函数(C语言函数调用原理).而在OC中,我们将函数调用称为消息发送.在编译时程序不查 ...