C#变成数据导入Excel和导出Excel
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#变成数据导入Excel和导出Excel相关的知识,希望对你有一定的参考价值。
excel 基础
applicationclass c = new applicationclass();
c.visible = false;
workbook wb = c.workbooks.add(xlwbatemplate.xlwbatworksheet);
//wb.saveas("c:/1.xls", null, null, null, null, xlsaveasaccessmode.xlnochange, xlsaveasaccessmode.xlnochange, null, null, null, null, null);
1、读取
using (filestream stream = new filestream(@"c:\客户资料.xls", filemode.open, fileaccess.read))
{
hssfworkbook workbook = new hssfworkbook(stream);
messagebox.show(workbook.getsheetname(0));
}
2、遇到错误别慌,仔细看错误信息。可能遇到
此文来自: 马开东博客 转载请注明出处 网址: http://www.makaidong.com
的问题:文件被其他进程占用。
3、npoi处理wps生成的xls有问题。
读取excel
private void button1_click(object sender, eventargs e)
{
//using (filestream stream = new filestream(@"c:\book1.xls", filemode.open, fileaccess.read))
//{
// hssfworkbook workbook = new hssfworkbook(stream);
// messagebox.show(workbook.getsheetname(0));
//}
//using (filestream stream = new filestream(@"c:\book1.xls", filemode.open, fileaccess.read))
//{
// hssfworkbook workbook = new hssfworkbook(stream);
// hssfsheet sheet = workbook.getsheetat(0);
// hssfrow row = sheet.getrow(0);
// hssfcell cell1 = row.getcell(1);
// hssfcell cell0 = row.getcell(0);
// messagebox.show(cell1.numericcellvalue.tostring());
// messagebox.show(cell0.stringcellvalue.tostring());
//}
//using (filestream stream = new filestream(@"c:\book1.xls", filemode.open, fileaccess.read))
//{
// hssfworkbook workbook = new hssfworkbook(stream);
// hssfsheet sheet = workbook.getsheetat(0);
// hssfrow row = sheet.getrow(0);
// hssfcell cell1 = row.getcell(1);
// if (cell1.celltype == hssfcell.cell_type_string)
// {
// messagebox.show("字符串");
// }
// else if (cell1.celltype == hssfcell.cell_type_numeric)
// {
// messagebox.show("数字");
// }
//}
using (filestream stream = new filestream(@"c:\book1.xls", filemode.open, fileaccess.read))
{
hssfworkbook workbook = new hssfworkbook(stream);
hssfsheet sheet = workbook.getsheetat(0);
for (int i = 0; i <= sheet.lastrownum; i++)
{
hssfrow row = sheet.getrow(i);
hssfcell cell0 = row.getcell(0);
hssfcell cell1 = row.getcell(1);
messagebox.show(string.format("{0}的年龄是:{1}",cell0.stringcellvalue,cell1.numericcellvalue));
}
//messagebox.show(sheet.lastrownum.tostring());
}
}
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.io;
using npoi.hssf.usermodel;
using callcenterclient.dal;
using system.data.sqlclient;
namespace callcenterclient.customers
{
public partial class formcustmgr : form
{
public formcustmgr()
{
initializecomponent();
}
private void btnimportexcel _click(object sender, eventargs e)
{
//string filename = @"c:\khzl.xls";
string filename = txtfilename.text;//界面上敲的是什么就是什么,没有转义,转义是给编译器看的
try
{
using (filestream stream = new filestream(filename, filemode.open, fileaccess.read))
{
hssfworkbook workbook = new hssfworkbook(stream);
hssfsheet sheet = workbook.getsheetat(0);
for (int i = 1; i <= sheet.lastrownum; i++)//注意从第1行开始读,第一行是表头
{
hssfrow row = sheet.getrow(i);
hssfcell cellname = row.getcell(0);
hssfcell celltel = row.getcell(1);
hssfcell cellbuydate = row.getcell(2);
hssfcell cellcarno = row.getcell(3);
hssfcell cellbrno = row.getcell(4);
//sqlhelper.executenonquery("insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(newid(),@name,@telphone,@buydate,@carnum,@bracketnum)",
// new sqlparameter("name", cellname.stringcellvalue),
// new sqlparameter("telphone", celltel.stringcellvalue),
// new sqlparameter("buydate", cellbuydate.datecellvalue),
// new sqlparameter("carnum", cellcarno.stringcellvalue),
// new sqlparameter("bracketnum", cellbrno.stringcellvalue));//newid()写在sql语句综合 中,在c#看来就是普通字符串,把sql扔给sqlserver运行,sqlserver会识别这个函数
//sqlhelper.executenonquery("insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(" + newid() + ",@name,@telphone,@buydate,@carnum,@bracketnum)");//错误,注意区别。
sqlhelper.executenonquery("insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(newid(),@name,@telphone,@buydate,@carnum,@bracketnum)",
new sqlparameter("name", cellname.stringcellvalue),//易错:别写成new sqlparameter("name", cellname)
new sqlparameter("telphone", celltel.stringcellvalue),
new sqlparameter("buydate", cellbuydate.datecellvalue),
new sqlparameter("carnum", cellcarno.stringcellvalue),
new sqlparameter("bracketnum", cellbrno.stringcellvalue));
}
}
messagebox.show("导入成功!");
}
catch (ioexception ex)//抓住ioexception类型的异常(文件正在被打开等异常)
{
messagebox.show(ex.message);
}
}
private void btnimportexcel 2_click(object sender, eventargs e)
{
string filename = txtfilename.text;//界面上敲的是什么就是什么,没有转义,转义是给编译器看的
try
{
using (filestream stream = new filestream(filename, filemode.open, fileaccess.read))
{
hssfworkbook workbook = new hssfworkbook(stream);
hssfsheet sheet = workbook.getsheetat(0);
for (int i = 1; i <= sheet.lastrownum; i++)//注意从第1行开始读,第一行是表头
{
hssfrow row = sheet.getrow(i);
hssfcell cellname = row.getcell(0);
hssfcell celltel = row.getcell(1);
hssfcell cellbuydate = row.getcell(2);
hssfcell cellcarno = row.getcell(3);
hssfcell cellbrno = row.getcell(4);
//正确写法
int count = (int)sqlhelper.executescalar("select count(*) from t_customers where [email protected] or [email protected]", new sqlparameter("carnum", cellcarno.stringcellvalue),
new sqlparameter("bracketnum", cellbrno.stringcellvalue));
//是否其他数据库 中有这辆车
if (count > 0)
{
continue;
}
datetime buydate;
if (cellbuydate.celltype == hssfcell.cell_type_numeric)//日期类型
{
buydate = cellbuydate.datecellvalue;
}
else if (cellbuydate.celltype == hssfcell.cell_type_string)//2008年9月8号
{
string strbuydate = cellbuydate.stringcellvalue;
strbuydate = strbuydate.replace("号", "日");
buydate = convert.todatetime(strbuydate);
}
else
{
throw new exception("未知的购买日期单元格类型");
}
sqlhelper.executenonquery("insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(newid(),@name,@telphone,@buydate,@carnum,@bracketnum)",
new sqlparameter("name", cellname.stringcellvalue),//易错:别写成new sqlparameter("name", cellname)
new sqlparameter("telphone", celltel.stringcellvalue),
new sqlparameter("buydate", buydate),
new sqlparameter("carnum", cellcarno.stringcellvalue),
new sqlparameter("bracketnum", cellbrno.stringcellvalue));
//错误写法:一个sqlparameter只能被一个command使用,只能添加一次
//sqlparameter pcarnum = new sqlparameter("carnum", cellcarno.stringcellvalue);
//int count = (int)sqlhelper.executescalar("select count(*) from t_customers where [email protected] or [email protected]", pcarnum,
// new sqlparameter("bracketnum", cellbrno.stringcellvalue));
////是否其他数据库 中有这辆车
//if (count > 0)
//{
// continue;
//}
//sqlhelper.executenonquery("insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(newid(),@name,@telphone,@buydate,@carnum,@bracketnum)",
// new sqlparameter("name", cellname.stringcellvalue),//易错:别写成new sqlparameter("name", cellname)
// new sqlparameter("telphone", celltel.stringcellvalue),
// new sqlparameter("buydate", cellbuydate.datecellvalue),
// pcarnum,
// new sqlparameter("bracketnum", cellbrno.stringcellvalue));
//影响的行数指的是修改了(update、delete等)的数据的行数,而不是select结果集的行数
//int count =sqlhelper.executenonquery("select * from t_customers where [email protected] or [email protected]",new sqlparameter("carnum",cellcarno.stringcellvalue),
// new sqlparameter("bracketnum", cellbrno.stringcellvalue));
////是否其他数据库 中有这辆车
//if (count > 0)
//{
// continue;
//}
//sqlhelper.executenonquery("insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(newid(),@name,@telphone,@buydate,@carnum,@bracketnum)",
// new sqlparameter("name", cellname.stringcellvalue),//易错:别写成new sqlparameter("name", cellname)
// new sqlparameter("telphone", celltel.stringcellvalue),
// new sqlparameter("buydate", cellbuydate.datecellvalue),
// new sqlparameter("carnum", cellcarno.stringcellvalue),
// new sqlparameter("bracketnum", cellbrno.stringcellvalue));
}
}
messagebox.show("导入成功!");
}
catch (ioexception ex)//抓住ioexception类型的异常(文件正在被打开等异常)
{
messagebox.show(ex.message);
}
}
private void button1_click(object sender, eventargs e)
{
try
{
importexcel 3();
messagebox.show("导入成功!");
}
catch (ioexception ex)//抓住ioexception类型的异常(文件正在被打开等异常)
{
messagebox.show(ex.message);
}
}
private void importexcel 3()
{
string filename = txtfilename.text;//界面上敲的是什么就是什么,没有转义,转义是给编译器看的
using (filestream stream = new filestream(filename, filemode.open, fileaccess.read))
{
hssfworkbook workbook = new hssfworkbook(stream);
hssfsheet sheet = workbook.getsheetat(0);
using (sqlconnection conn = new sqlconnection(sqlhelper.connstr))
{
conn.open();
for (int i = 1; i <= sheet.lastrownum; i++)//注意从第1行开始读,第一行是表头
{
hssfrow row = sheet.getrow(i);
hssfcell cellname = row.getcell(0);
hssfcell celltel = row.getcell(1);
hssfcell cellbuydate = row.getcell(2);
hssfcell cellcarno = row.getcell(3);
hssfcell cellbrno = row.getcell(4);
//正确写法
int count = (int)sqlhelper.executescalar(conn,"select count(*) from t_customers where [email protected] or [email protected]", new sqlparameter("carnum", cellcarno.stringcellvalue),
new sqlparameter("bracketnum", cellbrno.stringcellvalue));
//是否其他数据库 中有这辆车
if (count > 0)
{
continue;
}
datetime buydate;
if (cellbuydate.celltype == hssfcell.cell_type_numeric)//日期类型
{
buydate = cellbuydate.datecellvalue;
}
else if (cellbuydate.celltype == hssfcell.cell_type_string)//2008年9月8号
{
string strbuydate = cellbuydate.stringcellvalue;
strbuydate = strbuydate.replace("号", "日");
buydate = convert.todatetime(strbuydate);
}
else
{
throw new exception("未知的购买日期单元格类型");
}
sqlhelper.executenonquery(conn, "insert into t_customers(id,name,telphone,buydate,carnum,bracketnum) values(newid(),@name,@telphone,@buydate,@carnum,@bracketnum)",
new sqlparameter("name", cellname.stringcellvalue),//易错:别写成new sqlparameter("name", cellname)
new sqlparameter("telphone", celltel.stringcellvalue),
new sqlparameter("buydate", buydate),
new sqlparameter("carnum", cellcarno.stringcellvalue),
new sqlparameter("bracketnum", cellbrno.stringcellvalue));
}
}
}
}
private void btnexporttoexcel 1_click(object sender, eventargs e)
{
if (savefiledlg.showdialog() != dialogresult.ok)
{
return;
}
hssfworkbook workbook = new hssfworkbook();
hssfsheet sheet = workbook.createsheet();
//姓名 电话 购买日期 车号 车架号
//别用dataset,因为数据量可能会非常大,如果用dataset会非常占内存。
using (sqlconnection conn = new sqlconnection(sqlhelper.connstr))
{
conn.open();
using (sqlcommand cmd = conn.createcommand())
{
cmd.commandtext = "select * from t_customers";
using (sqldatareader reader = cmd.executereader())
{ //todo:加表头。
int rownum = 0;//行号
while (reader.read())
{
string name = reader.getstring(reader.getordinal("name"));
string telphone = reader.getstring(reader.getordinal("telphone"));
datetime buydate = reader.getdatetime(reader.getordinal("buydate"));
string carnum = reader.getstring(reader.getordinal("carnum"));
string brnum = reader.getstring(reader.getordinal("bracketnum"));
hssfrow row = sheet.createrow(rownum);//创建第rownum行
row.createcell(0, hssfcell.cell_type_string).setcellvalue(name);
row.createcell(1, hssfcell.cell_type_string).setcellvalue(telphone);
row.createcell(2, hssfcell.cell_type_string).setcellvalue(buydate.toshortdatestring());
row.createcell(3, hssfcell.cell_type_string).setcellvalue(carnum);
row.createcell(4, hssfcell.cell_type_string).setcellvalue(brnum);
rownum++;
}
}
}
}
using (filestream stream = new filestream(savefiledlg.filename, filemode.openorcreate, fileaccess.readwr ite))
{
workbook.write(stream);
}
messagebox.show("保存成功!");
}
private void formcustmgr_load(object sender, eventargs e)
{
this.t_customerstableadapter1.fill(this.datasetcustomers1.t_customers);
}
private void btnaddnew_click(object sender, eventargs e)
{
datarowview drv = bscustomers.addnew() as datarowview;
callcenterclient.dal.datasetcustomers.t_customersrow custrow = drv.row as callcenterclient.dal.datasetcustomers.t_customersrow;
custrow.id = guid.newguid();
}
private void btnsave_click(object sender, eventargs e)
{
t_customerstableadapter1.update(this.datasetcustomers1.t_customers);
}
}
} mmmm写入excel
hssfworkbook workbook = new hssfworkbook();
hssfsheet sheet = workbook.createsheet();
hssfrow row = sheet.createrow(0);
row.createcell(0, hssfcell.cell_type_string).setcellvalue("hello");
row.createcell(1, hssfcell.cell_type_numeric).setcellvalue(3.14);
using (filestream stream = new filestream(@"c:\1.xls", filemode.openorcreate, fileaccess.readwr ite))
{
workbook.write(stream);
}
搜索此文相关文章:C#变成数据导入Excel和导出Excel
此文链接:http://www.makaidong.com/%E5%8D%9A%E5%AE%A2%E5%9B%AD%E6%B1%87/38169.shtml
转载请注明出处:C#变成数据导入Excel和导出Excel - 博客园
以上是关于C#变成数据导入Excel和导出Excel的主要内容,如果未能解决你的问题,请参考以下文章