excel 基础
•整个excel 表格叫工作表:workbook;工作表包含的叫页:sheet;行:row;单元格:cell。
•excel 中的电话号码问题,看起来像数字的字符串以半角单引号开头就没问题了。
•使用区域(usedrange):用excel 表的时候不一定是从最左上角的单元格开始用,为了减小文件尺寸,有使用区域的概念,excel 只存储使用区域。
程序处理excel 的技术
•ole automation:程序启动一个excel 进程,然后和excel 进程进行通讯来进行excel 的操作。优点:强大,能够使用excel 的所有功能,要求装excel ,微软最推荐这种用法,因为可以促进excel 的销量。会启动excel 进程,不适合于服务器(比如asp.net网站,安全性、效率)。参考资料http://www.makaidong.com/denylau/archive/2010/04/30/1725172.html
–演示一下,引用excel .interop,代码在备注
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);
•(*)把excel 当成其他数据库 ,使用microsoft.jet.oledb访问访问excel ,参考资料 http://tieba.baidu.com/f?kz=331569890 只适合于完全二维结构,功能最弱,很少用。不用装excel 。
•(*) openxml,微软提供的读写excel 的技术,优点和npoi差不多,不过只能处理xlsx格式文件。docx、pptx
•npoi、myxls等,npoi能够分析excel 文件的格式,能够进行常用excel 操作,不依赖于excel ,节省资源,没有安全性、性能的问题,在asp.net中用最合适。只能处理xls格式文件、不能处理xlsx这样的新版本excel 文件格式。
npoi组件的引入
•我们平时调用的类是已经添加到引用的,如果想调用系统内置的没有添加引用的其他dll(*严格的说是在gac中的assembly)就要添加引用,在【.net】选项卡中选择,对于另外一些第三方dll(*严格说是assembly)则需要点击【浏览】选项卡选择对应的dll文件。
•将npoi包解压到硬盘中,然后在项目中添加引用,浏览,将解压目录下的dll全部添加进来
•(*)poi是apache的一个java开源项目,npoi是poi在.net下的移植版本,很多.net的移植版本开源项目都是在原来的java版本名称前加上n,比如nhibernate 、ndoc、nunit、nant。
npoi起步
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()); } }
•读取字符串类型数据messagebox.show(sheet.getrow(3).getcell(4).stringcellvalue); 读取数字类型数据numericcellvalue。
•判断单元格数据类型:读取getcell(4).celltype,与hssfcell类中定义的常量比较即可。
•判断使用区域:结束行号:lastrownum
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 - 博客园