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 ...
随机推荐
- 【Codeforces 279C】Ladder
[链接] 我是链接,点我呀:) [题意] 题意 [题解] 设pre[i]表示i往前一直递增能递增多远 设aft[i]表示i往后一直递增能递增多远 如果aft[l]+pre[r]>=(r-l+1) ...
- 【Codeforces 986B】Petr and Permutations
[链接] 我是链接,点我呀:) [题意] 题意 [题解] n为奇数时3n和7n+1奇偶性不同 n为偶数时也是如此 然后交换任意一对数 逆序对的对数的奇偶性会发生改变一次 求出逆序对 对n讨论得出答案. ...
- 解决win10磁盘占用过大的问题(亲测有效)
问题:打开任务管理器,经常会发现磁盘占用95%以上,电脑很卡,下面是解决方案 方法: 1.关闭家庭组. (1)搜索服务,找到“HomeGroupListener”服务,右键单击“属性”.在弹出属性界面 ...
- java 远程调用
1.webservice (soap+http) -aixs -axis2 -xfire—>cxf 2.webservice问题 -基于xml,xml效率,(数据传输效率,xml序列化效率) - ...
- PostGIS学习相关术语
POI 兴趣点(英语:point of interest,通常缩写成POI)乃是电子地图上的某个地标.景点,用以标示出该地所代表的政府部门.各行各业之商业机构(加油站.百货公司.超市.餐厅.酒店.便利 ...
- 记一次 Hibernate 插入数据中文乱码报错解决
错误描述 程序运行,向表中插入数据(包含中文)报错:\xE6\xB2\x88\xE9\x9B\xAA... 但是自己另外新建一个数据库手动插入数据中文正常,同样修改数据库,表的编码之后同样不行.而且 ...
- W3School Memcached教程(安装/基本操作/高级操作/命令)
来自W3School的Memcached教程,基本上涵盖了从安装到状态监控的教程. 不过最全的应该是官方提供在GitHub上的Wiki教程,一切的标准都来自官方,参考:https://github.c ...
- MySQL Workbench查看和修改表字段的Comment值
查看: 选择单个表->[右键]->[Table Inspector] 再选择Columns选项卡即可,把表格拉倒最后一列. 编辑: 选择单个表->[右键]->[Alter Ta ...
- [LeetCode] 035. Search Insert Position (Medium) (C++)
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Sea ...
- 分布式缓存Redis应用场景解析
Redis的应用场景非常广泛.虽然Redis是一个key-value的内存数据库,但在实际场景中,Redis经常被作为缓存来使用,如面对数据高并发的读写.海量数据的读写等. 举个例子,A网站首页一天有 ...