App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="sql" connectionString="Data Source=.;Initial Catalog=DBLQBZ;Integrated Security=True;"/>
</connectionStrings>
</configuration>

*.sc

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
//using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace 数据的导入导出_Excel文件_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string constr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
opd.Filter = "Excel 数据文件|*.xls";
opd.AddExtension = true;
opd.Title = "请选择Excel数据文件:";
opd.ShowDialog(this);
txtExcelPath.Text = opd.FileName;
} private void btnExport_Click(object sender, EventArgs e)
{
string sql = "select * from tblCusInfo";
using (SqlDataReader reader = this.ExportData(sql, null))
{
if (reader.HasRows)
{
using (FileStream fs = new FileStream(txtExcelPath.Text, FileMode.OpenOrCreate, FileAccess.Write))
{
//如果创建工作薄的时候指定了文件流,表示要打开一个Excel文件
//如果不指定文件流,则表示要创建一个新的工作薄(excel文件)
using (Workbook wb = new HSSFWorkbook())
{
Sheet sheet = wb.CreateSheet("Data");
Row name = sheet.CreateRow();
int fieldcount = reader.FieldCount;//列的数目
for (int i = ; i < fieldcount; i++)
{
name.CreateCell(i).SetCellValue(reader.GetName(i));//得到表列名
}
int rows = ;
while (reader.Read())
{
Row row = sheet.CreateRow(rows);
rows++;
for (int i = ; i < fieldcount; i++)//去除自动编号列
{
if (reader.IsDBNull(i))
{
row.CreateCell(i, CellType.BLANK);//空单元格
}
else
{//类型很多具体问题具体对待
string typename = reader.GetDataTypeName(i);//数据类型.ToString()
switch (typename)
{
case "int":
row.CreateCell(i, CellType.NUMERIC).SetCellValue(reader.GetInt32(i));
break;
case "bit":
row.CreateCell(i, CellType.BOOLEAN).SetCellValue(reader.GetBoolean(i));
break;
default:
row.CreateCell(i, CellType.STRING).SetCellValue(reader.GetString(i));
break;
}
}
}
}
wb.Write(fs);
}
MessageBox.Show("导出成功!");
}
}
}
} private void btnImport_Click(object sender, EventArgs e)
{
using (FileStream fs = File.OpenRead(txtExcelPath.Text))
{
using (Workbook wk = new HSSFWorkbook(fs))
{
string sql = "insert into tblCusInfo(姓名,手机,数量,固定电话,车号,车架号) values(@name,@mphone,@count,@phone,@carNum,@carStruNum);";
Sheet sheet = wk.GetSheetAt();
int len = sheet.LastRowNum;//这里行号是从0开始的,表格中实际上是1.2...
for (int i = ; i <= len; i++)//标题行省去
{
Row row = sheet.GetRow(i);
SqlParameter[] param = new SqlParameter[] {
new SqlParameter("@name",SqlDbType.NVarChar),
new SqlParameter("@mphone",SqlDbType.NVarChar),
new SqlParameter("@count",SqlDbType.Int),
new SqlParameter("@phone",SqlDbType.NVarChar),
new SqlParameter("@carNum",SqlDbType.NVarChar),
new SqlParameter("@carStruNum",SqlDbType.NVarChar)};
for (int j = ; j < row.LastCellNum; j++)
{
//Excel中空单元格不能用如下方法判断
//1.若单元格格式是:字符串类型
//会报错:未将对象引用设置到对象的实例。
/* string value = row.GetCell(j).ToString();
if (value != string.Empty)
{
param[j].Value = value;
}
//2.若单元格的格式是:数值类型
//空单元格被转换成:"";
if (row.GetCell(j)!=null)
{
string value = row.GetCell(j).ToString();
param[j].Value = value;
}*/
//最好的方法是判断类型
if (row.GetCell(j) != null && row.GetCell(j).CellType != CellType.BLANK)
{
string value = row.GetCell(j).ToString();
param[j].Value = value;
}
else
{
param[j].Value = DBNull.Value;
}
}
this.ImportData(sql, param);
}
}
MessageBox.Show("数据导入成功!");
}
} private SqlDataReader ExportData(string sql, SqlParameter[] param)
{
//这里用using链接会释放的
SqlConnection con = new SqlConnection(constr); using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (param != null)
{
cmd.Parameters.AddRange(param);
}
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
} } private int ImportData(string sql, SqlParameter[] param)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (param != null)
{
cmd.Parameters.AddRange(param);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
}
}

Form.cs

namespace 数据的导入导出_Excel文件_
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnBrowse = new System.Windows.Forms.Button();
this.lblExcelPath = new System.Windows.Forms.Label();
this.txtExcelPath = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnExport = new System.Windows.Forms.Button();
this.btnImport = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// btnBrowse
//
this.btnBrowse.Location = new System.Drawing.Point(, );
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(, );
this.btnBrowse.TabIndex = ;
this.btnBrowse.Text = "浏览...";
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// lblExcelPath
//
this.lblExcelPath.AutoSize = true;
this.lblExcelPath.Location = new System.Drawing.Point(, );
this.lblExcelPath.Name = "lblExcelPath";
this.lblExcelPath.Size = new System.Drawing.Size(, );
this.lblExcelPath.TabIndex = ;
this.lblExcelPath.Text = "Excel文件路径:";
//
// txtExcelPath
//
this.txtExcelPath.Location = new System.Drawing.Point(, );
this.txtExcelPath.Name = "txtExcelPath";
this.txtExcelPath.Size = new System.Drawing.Size(, );
this.txtExcelPath.TabIndex = ;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.lblExcelPath);
this.groupBox1.Controls.Add(this.txtExcelPath);
this.groupBox1.Controls.Add(this.btnBrowse);
this.groupBox1.Location = new System.Drawing.Point(, );
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(, );
this.groupBox1.TabIndex = ;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Excel文件路径选择";
//
// btnExport
//
this.btnExport.Location = new System.Drawing.Point(, );
this.btnExport.Name = "btnExport";
this.btnExport.Size = new System.Drawing.Size(, );
this.btnExport.TabIndex = ;
this.btnExport.Text = "数据导出";
this.btnExport.UseVisualStyleBackColor = true;
this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
//
// btnImport
//
this.btnImport.Location = new System.Drawing.Point(, );
this.btnImport.Name = "btnImput";
this.btnImport.Size = new System.Drawing.Size(, );
this.btnImport.TabIndex = ;
this.btnImport.Text = "数据导入";
this.btnImport.UseVisualStyleBackColor = true;
this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.btnImport);
this.Controls.Add(this.btnExport);
this.Controls.Add(this.groupBox1);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.Label lblExcelPath;
private System.Windows.Forms.TextBox txtExcelPath;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnExport;
private System.Windows.Forms.Button btnImport;
}
}

项目文件和NPOI***.dll文件和测试数据文件:http://pan.baidu.com/s/1c0d3N2K

NPOI 操作数据库中数据的导入导出(Excel.xls文件) 和null数据的处理。的更多相关文章

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

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

  2. 使用PHPExcel导入导出excel格式文件

    使用PHPExcel导入导出excel格式文件  作者:zccst  因为导出使用较多,以下是导出实现过程.  第一步,将PHPExcel的源码拷贝到项目的lib下  文件包含:PHPExcel.ph ...

  3. 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...

  4. winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    1.通过NUGET管理器下载nopi,在引入命令空间 using System; using System.Collections.Generic; using System.Text; using ...

  5. NPOI、MyXls、Aspose.Cells 导入导出Excel(转)

    Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导s出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你 ...

  6. java poi导出EXCEL xls文件代码

    String _currentPage = request.getParameter("currentPage"); Integer currentPage = 0; if(_cu ...

  7. java中使用poi导入导出excel文件_并自定义日期格式

    Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...

  8. asp.net core web的导入导出excel功能

    这里主要记录下asp.net core web页面上进行导入导出excel的操作. 主要是导入,因为现在使用的很多前端框架(例如kendo ui)本身就有导出的功能. 这里使用到EPPlus.Core ...

  9. C#用Infragistics 导入导出Excel(一)

    最近项目中有数据的导入导出Excel的需求,这里做简单整理. 公司用的是Infragistics的产品,付费,不需要本地安装Office. 有需要的朋友可以下载 Infragistics.2013.2 ...

随机推荐

  1. Java实现 LeetCode 363 矩形区域不超过 K 的最大数值和

    363. 矩形区域不超过 K 的最大数值和 给定一个非空二维矩阵 matrix 和一个整数 k,找到这个矩阵内部不大于 k 的最大矩形和. 示例: 输入: matrix = [[1,0,1],[0,- ...

  2. 第三届蓝桥杯JavaB组国(决)赛真题

    解题代码部分来自网友,如果有不对的地方,欢迎各位大佬评论 题目1.数量周期 [结果填空](满分9分) 复杂现象背后的推动力,可能是极其简单的原理.科学的目标之一就是发现纷繁复杂的自然现象背后的简单法则 ...

  3. java实现第六届蓝桥杯密文搜索

    密文搜索 福尔摩斯从X星收到一份资料,全部是小写字母组成. 他的助手提供了另一份资料:许多长度为8的密码列表. 福尔摩斯发现,这些密码是被打乱后隐藏在先前那份资料中的. 请你编写一个程序,从第一份资料 ...

  4. (一)c++之细解 const 与 static

    const成员变量与const成员函数与const对象 static成员变量与static成员函数与static全局变量 const成员变量 1. const用于类中成员变量时,将类成员变为只读属性( ...

  5. NetAnalyzer笔记 之 十四 NetAnalyzer 6.0 的使用方法 -- 3.协议分析与统计

    数据分析 完成了数据的抓取,那么接下来就是NetAnalyzer的第二个重点部分了,协议分析作为整个软件的核心之一,在最新的NetAnalyzer中已经得到了巨大的提升.NetAnalyzer中协议分 ...

  6. 00-01.Kali Linux 2020.1修改root用户密码

    安装Kali Linux 2020.1系统后,需要使用root用户权限安装软件. 由于VMWare版本的root用户默认密码未知,所以需要在单用户模式下重新设置root用户密码.操作步骤如下: 启动K ...

  7. 千万不要更新网易云音乐UWP!!!!!

    网易云音乐UWP没了!!! 现在 Micrsoft Store 里面的是垃圾 Win32 转置版!!!! 万不可更新!!! 若已经更新,还有救回来的办法:下载 https://lanzous.com/ ...

  8. 设计一个简单的多线程(Fecit)_1

    D6高级编程,Fecit ,学习里面关于线程创建的一个例子.,按照那个例子做的,不过本人喜欢将线程实现部分作为单独的单元,主线程再调用它. unit Unit1; interface uses Win ...

  9. 2019-02-07 selenium...

    今天是超级郁闷的一天 看教程 下了mysql-----配置-----不会----查资料------2小时后 mongodb-----配置------不会------查资料------1小时后 然后是各 ...

  10. docker 容器命令

    语法docker run [OPTIONS] IMAGE [COMMAND] [ARG...] OPTIONS说明: -a stdin: 指定标准输入输出内容类型,可选 STDIN/STDOUT/ST ...