C#学习-处理Excel
首先先了解下一个Excel文件的组成
1.一个Excel包含多个工作表(Sheet)
2.一个工作表(Sheet)包含多行(Row)
3.一行(Row)包含多个单元格(Cell)
如何判断一个单元格中的数据是数字类型,还是字符串类型?
|
字符串在左边,数值类型在右边 如果单元格式string类型,则用ToString() |


工具准备:
两个程序集NOPI.dll和Ionic.Zip.dll
对以上程序集的介绍
描述工作簿的类型:IWorkbook(接口),HSSFWorkbook(具体实现类)
描述工作表的类型:ISheet(接口),HSSFSheet(具体实现类)
1.读取Excel中文件
Student.xls文件如下

输出结果如下

代码
private void ReadExcel( )
{
//1.将Excel读到文件流中
using (FileStream fsRead=File.OpenRead("Student.xls"))
{
//2.根据文件流,创建一个工作簿对象(workbook)
IWorkbook wk=new HSSFWorkbook(fsRead);
//3.读取工作簿中的工作表
for (int i = 0; i < wk.NumberOfSheets; i++)
{
//3.1根据索引,获取一个工作表
ISheet sheet = wk.GetSheetAt(i);
//3.2输出工作表的名称
Console.WriteLine("====={0}=====",sheet.SheetName);
//4.遍历工作表每一行的数据
for (int r= 0; r <=sheet.LastRowNum; r++)
{
//获取当前行
IRow row = sheet.GetRow(r);
//5.遍历一行中的每一个单元格,当这一行为空时,row会返回null
if (row!=null)
{
//遍历一行的每一个单元格
for (int c = 0; c < row.LastCellNum; c++)
{
//创建单元格对象
ICell cell = row.GetCell(c);
//如果单元格未使用,则为null
if (cell!=null)
{
Console.Write(cell.ToString()+"\t");
}
}
}
Console.WriteLine();
}
}
}
}
2.写入Excel
private void WriteExcel( )
{
List<Person>listPersons=new List<Person>()
{
new Person(){Name="张三 1",Age=11,Gender='男'},
new Person(){Name="张三 2",Age=21,Gender='女'},
new Person(){Name="张三 3",Age=31,Gender='男'},
new Person(){Name="张三 4",Age=41,Gender='女'}
};
//1.创建Workbook对象
IWorkbook wk=new HSSFWorkbook();
//2.创建工作表对象
ISheet sheet = wk.CreateSheet("Persons");
//3.向工作表中添加行
for (int i = 0; i <= listPersons.Count-1; i++)
{
IRow row = sheet.CreateRow(i);
row.CreateCell(0).SetCellValue(listPersons[i].Name);
row.CreateCell(1).SetCellValue(listPersons[i].Age);
row.CreateCell(2).SetCellValue(listPersons[i].Gender.ToString());
}
using (FileStream writer=File.OpenWrite("Persons.xls"))
{
wk.Write(writer);
}
Console.WriteLine("ok");
}
查看Excel文件

3.表中数据读到Excel
数据库中列的类型
其中Age为int类型,而且为可空类型


代码
private void TableToExcel( )
{
//1.读取数据
string strSql = "select * from Persons";
using (SqlDataReader reader=SQLHelper.ExecuteReader(strSql,CommandType.Text))
{
if (reader.HasRows)
{
IWorkbook wk=new HSSFWorkbook();
ISheet sheet = wk.CreateSheet("Person1");
int rowIndex = 0;
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
//数据库中Age为可空类型
int? age = reader.IsDBNull(2) ? null : (int?) reader.GetInt32(2);
string gender = reader.GetString(3); IRow row = sheet.CreateRow(rowIndex);
rowIndex++; //向行中创建单元格
row.CreateCell(0).SetCellValue(id);
row.CreateCell(1).SetCellValue(name);
//对于数据库中可空的类型
ICell cellAge = row.CreateCell(2);
if (age == null)
{
//设置单元格的数据类型为Blank,即空单元格
cellAge.SetCellType(CellType.BLANK);
}
else
{
cellAge.SetCellValue((int)age);
}
row.CreateCell(3).SetCellValue(gender);
}
using (FileStream write=File.OpenWrite("TablePersons.xls"))
{
wk.Write(write);
}
}
}
Console.WriteLine("ok");
}
输出结果

4.Excel中数据读取到数据库中
Excel中数据

代码运行后,数据库中数据

代码
private void ExcelToTable( )
{
using (FileStream read=File.OpenRead("Persons.xls"))
{
//1.创建工作簿对象
IWorkbook wk=new HSSFWorkbook(read);
//2.读取第一张工作表
ISheet sheet = wk.GetSheetAt(0);
string strSql = "insert into Persons values(@Name,@Age,@Gender)";
//遍历工作表中的每一行:从0开始
for (int i = 0; i <= sheet.LastRowNum-1; i++)
{
//遍历每一行中的每一个单元格:从0开始
//字符串类型
IRow row = sheet.GetRow(i);
string name = row.GetCell(0).StringCellValue;
//可空类型
ICell cellAge = row.GetCell(1);
int? age = null;
if (cellAge != null && cellAge.CellType != CellType.BLANK)
{
age = Convert.ToInt32(cellAge.NumericCellValue);
}
//字符类型
char[] genders = row.GetCell(2).StringCellValue.ToCharArray();
char gender = genders[0]; SqlParameter[] paras=new SqlParameter[]
{
new SqlParameter("@Name",name),
new SqlParameter("@Age",age==null?DBNull.Value:(object)age),
new SqlParameter("@Gender",gender),
};
SQLHelper.ExecuteNonquery(strSql, CommandType.Text, paras);
}
}
Console.WriteLine("ok");
}
C#学习-处理Excel的更多相关文章
- ArcGIS学习记录-Excel和Txt中XY点数据生成点Shape文件方法
(一)Excel中XY点数据生成点Shape文件方法 1.Excel表如下: 2.点击ArcGIS中的"+"号按钮,添加数据.选择第一步中制作好的Excel文件,点击Add按钮 ...
- Python学习笔记-EXCEL操作
环境Python3 创建EXCEL,覆盖性创建 #conding=utf-8 import xlwt def BuildExcel(ExcelName,SheetName,TitleList,Data ...
- python学习,excel操作之xlrd模块常用操作
import xlrd ##工作表## #打开excel f = xlrd.open_workbook("test.xlsx") file = f.sheet_by_name(&q ...
- Asp.net core 学习笔记 (Excel 读写)
EPPlus 已经支持 .net core 了 https://www.nuget.org/packages/EPPlus https://github.com/JanKallman/EPPlus 写 ...
- VSTO学习(二)——Excel对象模型
要开发Excel的项目,就自然少不了对Excel对象模型的了解了,只有了解Excel对象模型,这样才能更好地对Excel进行处理.下面先给出一张Excel对象模型的图: 下面就具体对上图中的各个对象做 ...
- Python基础学习七 Excel操作
python操作excel,python操作excel使用xlrd.xlwt和xlutils模块, xlrd模块是读取excel的,xlwt模块是写excel的,xlutils是用来修改excel的. ...
- Python学习之==>Excel操作
一.简介 使用Python读.写.修改excel分别需要用到xlrd.xlwt以及xlutils模块,这几个模块使用pip安装即可. 二.读excel import xlrd book = xlrd. ...
- QTP学习笔记--Excel数据源
直接读取Excel表格的function摘自此处http://www.51testing.com/html/40/307440-827863.html 特此感谢! Excel作为QTP自动化测试的数 ...
- java学习(四) excel读取
private static void readExcel() { String filePath = "C:/Standardzid.xls"; File file = new ...
随机推荐
- Docker定制镜像
定制镜像 除了使用定制好的镜像外,我们也可以通过定制实现符合自己环境的镜像. 在docker里面通过build方法来生成镜像,在生成镜像之前,我们需要一个Dockerfile脚本,脚本中包含的是一条一 ...
- 如何绘制caffe网络训练曲线
本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/51774966 当我们设计好网络结构后, ...
- Win32编程API 基础篇 -- 5.使用资源
使用资源 你可能想参考教程结尾的附近,为了获得跟VC++和BC++资源相关的信息. 在我们讲得更加深入之前,我将大致讲解一下资源的主题,这样在每个小节中我就不必再去重讲一遍了.在这一小节中,你不需要编 ...
- Frame Stacking 拓扑排序 图论
Description Consider the following 5 picture frames placed on an 9 x 8 array. ........ ........ .... ...
- 浪潮服务器装机RAID
下面是在装浪潮服务器NF8480M5收集的资料,但是NF8480M5服务器没有网上说的webBIOS界面需要按住DEL进BIOS,将启动都禁止了再重启,进入页面配置. http://blog.51ct ...
- - > 动规讲解基础讲解七——最长单增子序列
(LIS Longest Increasing Subsequence)给定一个数列,从中删掉任意若干项剩余的序列叫做它的一个子序列,求它的最长的子序列,满足子序列中的元素是单调递增的. 例如给定序列 ...
- PayPal加密证书.pem的生成
How do I create a public certificate for use with PayPal Encrypted Website Payments? Before you ca ...
- 编程规范(一 之kmalloc,fflush,fclose,char_init)
1. kmalloc函数接口: 在我们使用的时候常常使用该接口,可是我们非常少注意过这个接口的一些比較重要的 内核接口.比如: /*申请一个HASH表的大小*/ #define HASH_MALLOC ...
- [Angular] New in V6.1
Router Scroll Position Restoration: remember and restore scroll position as the user navigates aroun ...
- [LeetCode] 035. Search Insert Position (Medium) (C++)
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Sea ...