C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

时间:2022-03-29 10:46:26

一、Excel理论知识

最新版NPOI2.4.1链接:https://pan.baidu.com/s/1iTgJi2hGsRQHyw2S_4dIUw  提取码:adnq

• 整个Excel表格叫做工作簿:WorkBook

• 工作簿由以下几部分组成

  a.页(Sheet);

  b.行(Row);

  c.单元格(Cell);

二、处理Excel的技术

•OLE Automation:程序启动一个Excel进程,然后和Excel进程进行通讯来运行Excel的操作。

  优点:强大,Excel能实现的功能,都可以实现

  缺点:必须装Excel

•把Excel当成数据库,使用Microsoft.Jet.OleDb访问Excel,只适合二维结构,功能少,不用装Excel

•OpenXML,微软提供的读写Excel的技术,只能处理xlsx格式文件

•NPOI、MyXls,能够分析Excel文件的格式,能够进行常用Excel操作,不依赖于Excel,节省资源,没有安全性和性能的问题。只能处理xls格式文件、不能处理xlsx这样的新版本Excel文件格式。处理xlsx用OpenXML

 描述工作簿的类:IWorkbook(接口)、HSSFWorkbook(具体实现类)

 描述工作表的类:ISheet(接口)、HSSFSheet(具体实现类)

三、NPOI导出

方式一(默认导出位置)

         private void button1_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>() {
new Person(){Name="张三",Age="15",Email="123@qq.com" },
new Person(){Name="李四",Age="16",Email="456@qq.com" },
new Person(){Name="王五",Age="17",Email="789@qq.com" }
};
// 引用命名空间
// using NPOI.HSSF.UserModel;
// using NPOI.SS.UserModel;
// using System.IO;
//将List集合中的内容导出到Excel中
//1、创建工作簿对象
IWorkbook wkBook = new HSSFWorkbook();
//2、在该工作簿中创建工作表对象
ISheet sheet = wkBook.CreateSheet("人员信息"); //Excel工作表的名称
//2.1向工作表中插入行与单元格
for (int i = 0; i < list.Count; i++)
{
//在Sheet中插入创建一行
IRow row = sheet.CreateRow(i);
//在该行中创建单元格
//方式一
//ICell cell = row.CreateCell(0);
//cell.SetCellValue(list[i].Name);
//方式二
row.CreateCell(0).SetCellValue(list[i].Name); //给单元格设置值:第一个参数(第几个单元格);第二个参数(给当前单元格赋值)
row.CreateCell(1).SetCellValue(list[i].Age);
row.CreateCell(2).SetCellValue(list[i].Email);
}
//3、写入,把内存中的workBook对象写入到磁盘上
FileStream fsWrite = File.OpenWrite("Person.xls"); //导出时Excel的文件名
wkBook.Write(fsWrite);
MessageBox.Show("写入成功!", "提示");
fsWrite.Close(); //关闭文件流
wkBook.Close(); //关闭工作簿
fsWrite.Dispose(); //释放文件流
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _01NPOI的写入
{
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Email { get; set; }
}
}

Person类

方式二(更友好的一种方式,用户可以指定导出位置)推荐

         private void button3_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>() {
new Person(){Name="张三",Age="",Email="123@qq.com" },
new Person(){Name="李四",Age="",Email="456@qq.com" },
new Person(){Name="王五",Age="",Email="789@qq.com" }
};
//创建文件
string fileName = "人员信息表";
string saveFilePath = ""; //导出时文件的路径
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls"; //默认文件扩展名
saveDialog.Filter = "Excel文件|*.xls"; //文件名筛选字符串
saveDialog.FileName = fileName; //导出文件名称
saveDialog.ShowDialog(); //显示窗口
saveFilePath = saveDialog.FileName; //文件路径
// 引用命名空间
// using NPOI.HSSF.UserModel;
// using NPOI.SS.UserModel;
// using System.IO;
//将List集合中的内容导出到Excel中
//1、创建工作簿对象
IWorkbook wkBook = new HSSFWorkbook();
//2、在该工作簿中创建工作表对象
ISheet sheet = wkBook.CreateSheet("人员信息"); //Excel工作表的名称
//2.1向工作表中插入行与单元格
for (int i = ; i < list.Count; i++)
{
//在Sheet中插入创建一行
IRow row = sheet.CreateRow(i);
//在该行中创建单元格
//方式一
//ICell cell = row.CreateCell(0);
//cell.SetCellValue(list[i].Name);
//方式二
row.CreateCell().SetCellValue(list[i].Name); //给单元格设置值:第一个参数(第几个单元格);第二个参数(给当前单元格赋值)
row.CreateCell().SetCellValue(list[i].Age);
row.CreateCell().SetCellValue(list[i].Email);
}
//3、写入,把内存中的workBook对象写入到磁盘上
FileStream fsWrite = new FileStream(saveFilePath,FileMode.Create);
wkBook.Write(fsWrite);
MessageBox.Show("写入成功!", "提示");
fsWrite.Close(); //关闭文件流
wkBook.Close(); //关闭工作簿
fsWrite.Dispose(); //释放文件流
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _01NPOI的写入
{
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Email { get; set; }
}
}

Person类

方式三、导出dataGridView数据

         public static void ExportExcel(string fileName, DataGridView dgv)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName; HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream(); NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1"); int rowCount = dgv.Rows.Count+;
int colCount = dgv.Columns.Count;
int r1;
NPOI.SS.UserModel.IRow dataRow1 = sheet.CreateRow(); for (int i = ; i < rowCount; i++)
{
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(i);
for (int j = ; j < colCount; j++)
{
if (i == )
{
r1 = i;
}
else
{
r1 = i - ;
}
if (dgv.Columns[j].Visible && dgv.Rows[r1].Cells[j].Value != null)
{
NPOI.SS.UserModel.ICell cell = dataRow.CreateCell(j-);
if (i == )
{
cell.SetCellValue(dgv.Columns[j].HeaderCell.Value.ToString());
continue;
}
cell.SetCellValue(dgv.Rows[r1].Cells[j].FormattedValue.ToString());
}
else
{
NPOI.SS.UserModel.ICell cell = dataRow.CreateCell(j-);
cell.SetCellValue("");
}
}
} workbook.Write(ms);
FileStream file = new FileStream(saveFileName, FileMode.Create);
workbook.Write(file);
file.Close();
workbook = null;
ms.Close();
ms.Dispose();
}

DGV中数据导出Excel

四、NPOI读取Excel内容

         private void button2_Click(object sender, EventArgs e)
{
//需要读取的文件:人员表.xls
// 创建文件
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel文件|*.xls";
ofd.ShowDialog();
string filePath = ofd.FileName;
FileStream fsRead=null;
IWorkbook wkBook = null;
if (filePath != "")
{
//1、创建一个工作簿workBook对象
fsRead = new FileStream(filePath, FileMode.Open);
//将人员表.xls中的内容读取到fsRead中
wkBook = new HSSFWorkbook(fsRead);
//2、遍历wkBook中的每个工作表Sheet
for (int i = ; i < wkBook.NumberOfSheets; i++)
{
//获取每个工作表对象
ISheet sheet = wkBook.GetSheetAt(i);
//获取每个工作表的行
//foreach遍历 sheet.GetEnumerator
for (int r = ; r < sheet.LastRowNum; r++)
{
//获取工作表中的每一行
IRow currentRow = sheet.GetRow(r);
//遍历当前行中的每个单元格
for (int c = ; c < currentRow.LastCellNum; c++)
{
try
{
//获取每个单元格
ICell cell = currentRow.GetCell(c);
if (cell == null) //如果单元格为空时,程序会报错,这里判断提示用户,用try catch防止程序蹦
{
MessageBox.Show(string.Format("第{0}行,第{1}列单元格为空!",r,c));
}
CellType cType = cell.CellType; // 获取单元格中的类型
MessageBox.Show(cType.ToString());
//判断当前单元格的数据类型,可以拓展
switch (cType)
{
case CellType.Numeric: //数字
MessageBox.Show("我是数字");
break;
case CellType.String: //字符串
MessageBox.Show("我是字符串");
break;
case CellType.Boolean:
MessageBox.Show("我是布尔值");
break;
}
//获取单元格的值
//日期
DateTime date = cell.DateCellValue;
//数字
double num = cell.NumericCellValue;
//字符串
string str = cell.StringCellValue;
//布尔值
bool bl = cell.BooleanCellValue;
}
catch (Exception EX)
{ } }
}
}
}
else
{
MessageBox.Show("选择文件失败!","提示");
}
fsRead.Close();
wkBook.Close();
fsRead.Dispose(); }

五、数据库中数据,导出Excel

 private void button4_Click(object sender, EventArgs e)
{
// 需引用命名空间
// using System.Data.SqlClient;
// using NPOI.HSSF.UserModel;
// using NPOI.SS.UserModel;
// using System.IO;
//1、通过ado.net读取数据
string strSql = "SELECT * FROM Students";
SqlDataReader reader = sqlHelper.ExecuteReader(strSql,CommandType.Text);
if (reader.HasRows) //若有数据
{
//2、将读取到的数据写入到Excel中
//2.1创建工作簿WorkBook对象
IWorkbook wkBook = new HSSFWorkbook();
//2.2创建工作表
ISheet sheet = wkBook.CreateSheet("人员信息表"); //工作表名称
int rIndex = ;
while (reader.Read())
{
//每读取一条数据,就创建一行row
IRow currentRow = sheet.CreateRow(rIndex);
rIndex++;
int ID = reader.GetInt32();
string name = reader.GetString();
int age = reader.GetInt32();
//向行中创建单元格
currentRow.CreateCell().SetCellValue(ID); //第一个参数:单元格索引;第二个参数:给单元格赋值
currentRow.CreateCell().SetCellValue(name);
currentRow.CreateCell().SetCellValue(age);
}
//创建文件
string fileName = "人员信息表";
string saveFilePath = ""; //导出时文件的路径
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls"; //默认文件扩展名
saveDialog.Filter = "Excel文件|*.xls"; //文件名筛选字符串
saveDialog.FileName = fileName; //导出文件名称
saveDialog.ShowDialog(); //显示窗口
saveFilePath = saveDialog.FileName; //文件路径
//将workBook对象写入到磁盘上
FileStream fsWrite = new FileStream(saveFilePath, FileMode.Create);
wkBook.Write(fsWrite);
MessageBox.Show("数据导出成功!", "提示");
fsWrite.Close(); //关闭文件流
wkBook.Close(); //关闭工作簿
fsWrite.Dispose(); //释放文件流
}
else
{
MessageBox.Show("没有数据");
} //reader.Close();
}
         public static SqlDataReader ExecuteReader(string strSql, CommandType cmdType, params SqlParameter[] pms)
{
SqlDataReader sr = null;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
sr = cmd.ExecuteReader();
return sr;
}
catch (Exception EX)
{
MessageBox.Show(EX.Message.ToString());
}
finally
{
cmd.Dispose();
}
return sr;
}

函数

六、Excel数据导入数据库

数据库字段

C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

Excel数据(必须和数据库字段对上)

C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

         Thread th;  //声明公共变量
private void button5_Click(object sender, EventArgs e)
{
//因为要遍历Excel中的数据,我们这里用线程执行
// 需引入命名空间
//using System.Threading;
//using System.Data.SqlClient;
//using NPOI.HSSF.UserModel;
//using NPOI.SS.UserModel;
//using System.IO;
//创建文件
object filePath = ""; // 文件路径
OpenFileDialog ofd = new OpenFileDialog(); //创建文件
ofd.Filter = "Excel文件|*.xls";
ofd.ShowDialog();
filePath = ofd.FileName;
th = new Thread(inportData);
th.IsBackground = true; //将线程设置为后台进程
th.Start(filePath);
ofd.Dispose();
}
private void inportData(object filePath)
{
// 创建表副本 SELECT TOP 0 * INSERT INTO newTable FROM oldTable
//1、从Excel中读取数据
if (filePath.ToString() != "")
{
FileStream fsRead = new FileStream(filePath.ToString(), FileMode.Open);
//一、创建工作簿
IWorkbook workBook = new HSSFWorkbook(fsRead);
string insert_sql = "";
string insert_module = "INSERT INTO Student2 (id,name,age) VALUES ({0})";
StringBuilder sb = new StringBuilder();
for (int i = ; i < workBook.NumberOfSheets; i++)
{
//获取工作表
ISheet sheet = workBook.GetSheetAt(i);
for (int r = ; r <= sheet.LastRowNum; r++) //遍历当前工作表中的所有行
{
IRow currentRow = sheet.GetRow(r); //获取每一行
for (int c = ; c < currentRow.LastCellNum; c++) //遍历当前行中的所有列
{
//获取每个单元格
ICell cell = currentRow.GetCell(c);
//listCells.Add(cell);
sb.Append("'").Append(cell.ToString()).Append("',");
}
//拼接SQL语句
insert_sql += string.Format(insert_module, sb.ToString().Substring(, sb.ToString().Length - )) + ";";
sb.Clear();
//listCells.Clear();
}
}
//2、把读取到的数据插入到数据库
//执行SQL语句
int ret = sqlHelper.ExecuteNonQuery(insert_sql, CommandType.Text);
if (ret == )
{
MessageBox.Show("导入成功!");
}
else
{
MessageBox.Show("导入失败!");
}
fsRead.Close();
fsRead.Dispose();
}
else
{
MessageBox.Show("文件打开失败!");
}
}
         /// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="strSql">sql语句</param>
/// <param name="cmdType">CommandType.Text代表执行的SQL语句、CommandType.StoreProcedure代表执行的是存储过程</param>
/// <param name="pms">可变参数数组</param>
/// <returns></returns>
public static int ExecuteNonQuery(string strSql, CommandType cmdType, params SqlParameter[] pms)
{
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
conn.Open();
SqlTransaction trans = conn.BeginTransaction();
try
{
cmd.Transaction = trans;
int count = cmd.ExecuteNonQuery();
if (count > )
{
trans.Commit(); //提交事务
return ;
}
else
{
trans.Rollback(); //回滚事务
return -;
}
}
catch (Exception EX)
{
trans.Rollback(); //回滚事务
MessageBox.Show(EX.Message.ToString());
return -;
}
finally
{
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}

函数

导入成功!!!

C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

七、设置单元样式

 ICellStyle style = workbook.CreateCellStyle();//创建样式对象
IFont font = workbook.CreateFont(); //创建一个字体样式对象
font.FontName = "方正舒体"; //和excel里面的字体对应
font.Color = new HSSFColor.PINK().GetIndex();//颜色参考NPOI的颜色对照表(替换掉PINK())
font.IsItalic = true; //斜体
font.FontHeightInPoints = ;//字体大小
font.Boldweight = short.MaxValue;//字体加粗
style.SetFont(font); //将字体样式赋给样式对象
cell.CellStyle = style; //把样式赋给单元格

字体

 ICellStyle style=workbook.CreateCellStyle();
style.FillForegroundColor = ; //具体数字代表的颜色看NPOI颜色对照表
style.FillPattern = FillPatternType.SOLID_FOREGROUND;

单元格前景色

   行高:row.Height =  * ;    //行高为30

   列宽:sheet.SetColumnWidth(,  * )   //第4列的列宽为13

单元格宽高

     单元格合并后,样式以左上角的单元格为准

     //CellRangeAddress四个参数为:起始行,结束行,起始列,结束列

   sheet.AddMergedRegion(new CellRangeAddress(, , , ));

合并单元格

  style.Alignment = HorizontalAlignment.CENTER;

水平居中

     不需要写“=”号

   cell.CellFormula = "公式";

设置公式

 //上下左右

 styleFont.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
styleFont.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
styleFont.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
styleFont.BorderRight = NPOI.SS.UserModel.BorderStyle.THICK;

边框

-----------------------以下异常处理-----------------------

一、数据库中数据类型不同、为空时处理

数据库数据

C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

导出处理

         private void button1_Click(object sender, EventArgs e)
{
//1、通过ADO.NET读取数据
string strSql = "SELECT * FROM userInfo";
SqlDataReader reader = sqlHelper.ExecuteReader(strSql,CommandType.Text);
if (reader.HasRows)
{
//------创建文件开始------
string filePath = ""; //要导出的文件路径
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "Excel文件|*.xls";
saveFile.DefaultExt = "xls";
saveFile.FileName = "人员表";
DialogResult dResult= saveFile.ShowDialog(); //获取用户点击的按钮 保存/取消
filePath = saveFile.FileName; //获取导出路径
//------创建文件结果------
if (dResult == DialogResult.Cancel) //用户点击的按钮
{
MessageBox.Show("取消导出!");
return;
}
//创建工作簿
IWorkbook workBook = new HSSFWorkbook();
//创建工作表
ISheet sheet = workBook.CreateSheet("人员表"); // 设置工作表名称
#region 创建第一行,设置列名
//------------------------------------------------------------
//创建第一行,第一行表示列名
//循环查询出每一列
IRow rowHead = sheet.CreateRow();
for (int col = ; col < reader.FieldCount; col++)
{
rowHead.CreateCell(col).SetCellValue(reader.GetName(col)); //获取当前列的名字:reader.GetName(col)
}
//------------------------------------------------------------
#endregion
int rIndex = ; //为什么行的索引为1呢,因为没有列名
while (reader.Read())
{
IRow currentRow = sheet.CreateRow(rIndex); //创建行
int id = reader.GetInt32();
string user_id = reader.GetString();
string user_pwd = reader.GetString();
string user_name = reader.GetString();
DateTime? dTime = reader.IsDBNull() ? null : (DateTime?)reader.GetDateTime(); //声明时加"?":可空类型
int? num = reader.IsDBNull() ? null : (int?)reader.GetInt32();
currentRow.CreateCell().SetCellValue(id);
currentRow.CreateCell().SetCellValue(user_id);
currentRow.CreateCell().SetCellValue(user_pwd);
currentRow.CreateCell().SetCellValue(user_name);
//若嫌麻烦的童鞋,此处可以用for循环获取值,然后用switch分别判断单元格的类型,为了方便让大家理解,这里不用for循环遍历
//for (int i = 0; i < reader.FieldCount; i++)
//{
// string ret = reader.GetDataTypeName(i); // 获取读取到列的数据类型
// switch (ret)
// {
// case "string":
// break;
// case "int":
// break;
// }
//}
if (dTime == null)
{
//若果为NULL值,向Excel写入一个单元格,类型为Blank
currentRow.CreateCell().SetCellType(CellType.Blank);
}
else
{
currentRow.CreateCell().SetCellValue((DateTime)dTime);
}
if (num==null)
{
currentRow.CreateCell().SetCellType(CellType.Blank);
}
else
{
currentRow.CreateCell().SetCellValue((int)num);
}
rIndex++;
}
//写入Excel
FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate);
workBook.Write(fsRead);
MessageBox.Show("导出成功");
}
else
{
MessageBox.Show("没有数据");
}
//2、写入Excel
}

二、数据库列为日期类型,导出时

注:通过NPOI导出DateTime类型时,如果不转换为string,则需要设置一下单元格的格式

C#NPOI对Excel的操作、导入导出时异常处理、最全的NPOI资料在这里~

处理方法:

 #region 创建单元格
ICell cellLockDate = currentRow.CreateCell();
//赋值
cellLockDate.SetCellValue((DateTime)dTime);
#endregion
#region 设置样式
HSSFCellStyle cellstyle = (HSSFCellStyle)workBook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workBook.CreateDataFormat();
cellstyle.DataFormat = format.GetFormat("yyyy-mm-dd");
//赋值给单元格
cellLockDate.CellStyle = cellstyle;
#endregion

处理导出时日期格式

 第一种:日期格式

             cell.setCellValue(new Date(,,));
//set date format
HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
HSSFDataFormat format= demoWorkBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("yyyy年m月d日"));
cell.setCellStyle(cellStyle); 第二种:保留两位小数格式
cell.setCellValue(1.2);
HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
cell.setCellStyle(cellStyle); 这里与上面有所不同,用的是HSSFDataFormat.getBuiltinFormat()方法,之所以用这个,是因为0.00是Excel内嵌的格式,完整的Excel内嵌格式列表大家可以看这个窗口中的自定义列表: HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
style7.DataFormat = format.GetFormat("#,##0.00");//千分位,保留两位小数
这里就不一一列出了 第三种:货币格式 cell.setCellValue();
HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
HSSFDataFormat format= demoWorkBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("¥#,##0"));
cell.setCellStyle(cellStyle); 第四种:百分比格式 cell.setCellValue();
HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
cell.setCellStyle(cellStyle);
此种情况跟第二种一样 第五种:中文大写格式 cell.setCellValue();
HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
HSSFDataFormat format= demoWorkBook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("[DbNum2][$-804]0"));
cell.setCellStyle(cellStyle); 第六种:科学计数法格式 cell.setCellValue();
HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
cellStyle.setDataFormat( HSSFDataFormat.getBuiltinFormat("0.00E+00"));
cell.setCellStyle(cellStyle);
---------------------
作者:liangyaomu
来源:CSDN
原文:https://blog.csdn.net/liangyaomu/article/details/52871994
版权声明:本文为博主原创文章,转载请附上博文链接!

处理其他情况汇总

三、Excel导入数据库处理

本示例没有用线程,建议用线程操作

 private void button2_Click(object sender, EventArgs e)
{
String filePath = "";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel文件|*.xls";
DialogResult ret = ofd.ShowDialog();
if (DialogResult.OK == ret)
{
filePath = ofd.FileName;
FileStream fsRead = new FileStream(filePath,FileMode.Open);
//创建工作簿
IWorkbook workBook = new HSSFWorkbook(fsRead);
string insert_module = "INSERT INTO Students VALUES ({0})";
string insert_sql = "";
StringBuilder sb = new StringBuilder();
for (int w = ; w < workBook.NumberOfSheets; w++)
{
//获取工作簿中的每个工作表
ISheet sheet = workBook.GetSheetAt(w);
//遍历当前工作表中的行
for (int r = ; r <= sheet.LastRowNum; r++)
{
//获取当前行
IRow currentRow = sheet.GetRow(r);
if (currentRow!=null) //表示该行有对象
{
//遍历当前行中的单元格
for (int c = ; c < currentRow.LastCellNum; c++)
{
ICell currentCell = currentRow.GetCell(c);
//判断单元格是否为空
if (currentCell == null || currentCell.CellType == CellType.Blank || currentCell.ToString().Trim()=="")
{
//表示空值,需要往数据库中插入空值
sb.Append("'',");
}
else
{
CellType cType = currentCell.CellType;
#region 拼接SQL语句
switch (cType)
{
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(currentCell) == true) //单元格类型为数字,并且为日期类型
{
sb.Append("'").Append(currentCell.DateCellValue).Append("',");
}
else //不是日期类型
{
sb.Append("'").Append(currentCell.NumericCellValue).Append("',");
}
break;
case CellType.String:
sb.Append("'").Append(currentCell.StringCellValue).Append("',");
break;
}
#endregion
}
} //currentRow.LastCellNum
insert_sql += string.Format(insert_module, sb.ToString().Substring(, sb.ToString().Length - ))+";";
sb.Clear();
}
} //sheet.LastRowNum
}
int res = sqlHelper.ExecuteNonQuery(insert_sql.Substring(,insert_sql.Length-),CommandType.Text);
if (res == )
{
MessageBox.Show("导入成功");
}
else
{
MessageBox.Show("导入失败");
}
}
else
{
MessageBox.Show("请选择导入文件!");
}
}
 public static int ExecuteNonQuery(string strSql, CommandType cmdType, params SqlParameter[] pms)
{
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
conn.Open();
SqlTransaction trans = conn.BeginTransaction();
try
{
cmd.Transaction = trans;
int count = cmd.ExecuteNonQuery();
if (count > )
{
trans.Commit(); //提交事务
return ;
}
else
{
trans.Rollback(); //回滚事务
return -;
}
}
catch (Exception EX)
{
trans.Rollback(); //回滚事务
MessageBox.Show(EX.Message.ToString());
return -;
}
finally
{
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}

函数

项目链接:https://pan.baidu.com/s/150J59Z3XP2DroZDy9HYfFA

提取码:nkw1

有不懂的童鞋,欢迎下方留言~~~