电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

java實現Excel的導入導出

瀏覽:160日期:2022-05-29 13:00:55

本文實例為大家分享了java實現Excel導入導出的具體代碼,供大家參考,具體內容如下

一.Excel讀寫技術

java實現Excel的導入導出

區別:

java實現Excel的導入導出

二.jxl讀寫基礎代碼

1.從數據庫將數據導出到excel表格

public class JxlExcel {public static void main(String[] args) { //創建Excel文件 String[] title= {'姓名','課程名','分數'}; File file=new File('f:/sheet1.xls'); try { file.createNewFile(); //創建工作簿 WritableWorkbook workbook=Workbook.createWorkbook(file); //創建Sheet WritableSheet sheet=workbook.createSheet('表格一', 20); //第一行設置列名 Label label=null; for (int i = 0; i < title.length; i++) { label=new Label(i, 0, title[i]);//第一個參數為列,第二個為行 sheet.addCell(label); } Data data=new Data(); ResultSet rs=data.getString(); while(rs.next()) { System.out.println(rs.getString(1)); label=new Label(0,rs.getRow(),rs.getString(1)); sheet.addCell(label); label=new Label(1,rs.getRow(),rs.getString(2)); sheet.addCell(label); label=new Label(2,rs.getRow(),rs.getString(3)); sheet.addCell(label); } workbook.write(); workbook.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }} }

2.從Excel表格中讀取數據

public class JxlRead {public static void main(String[] args) { //創建workbook try { Workbook workbook=Workbook.getWorkbook(new File('f:/sheet1.xls')); //獲取第一個表格 Sheet sheet=workbook.getSheet(0); //獲取數據 for (int i = 0; i < sheet.getRows(); i++) { for (int j = 0; j < sheet.getColumns(); j++) { Cell cell=sheet.getCell(j, i); System.out.print(cell.getContents()+' '); } System.out.println(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}

三.Poi讀寫基礎代碼

//所需jar包:commons-io-2.2.jar;poi-3.11-20141221.jar//通過poi進行excel導入數據public class PoiExcel {public static void main(String[] args) throws SQLException { String title[]= {'名字','課程','分數'}; //1.創建Excel工作簿 HSSFWorkbook workbook=new HSSFWorkbook(); //2.創建一個工作表 HSSFSheet sheet=workbook.createSheet('sheet2'); //3.創建第一行 HSSFRow row=sheet.createRow(0); HSSFCell cell=null; //4.插入第一行數據 for (int i = 0; i < title.length; i++) { cell=row.createCell(i); cell.setCellValue(title[i]); } //5.追加數據 Data data=new Data(); ResultSet rs=data.getString(); while(rs.next()) { HSSFRow row2=sheet.createRow(rs.getRow()); HSSFCell cell2=row2.createCell(0); cell2.setCellValue(rs.getString(1)); cell2=row2.createCell(1); cell2.setCellValue(rs.getString(2)); cell2=row2.createCell(2); cell2.setCellValue(rs.getString(3)); } //創建一個文件,將Excel內容存盤 File file=new File('e:/sheet2.xls'); try { file.createNewFile(); FileOutputStream stream=FileUtils.openOutputStream(file); workbook.write(stream); stream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}

//將Excel表中內容讀取public class PoiRead {public static void main(String[] args) { //需要解析的Excel文件 File file=new File('e:/sheet2.xls'); try { //獲取工作簿 FileInputStream fs=FileUtils.openInputStream(file); HSSFWorkbook workbook=new HSSFWorkbook(fs); //獲取第一個工作表 HSSFSheet hs=workbook.getSheetAt(0); //獲取Sheet的第一個行號和最后一個行號 int last=hs.getLastRowNum(); int first=hs.getFirstRowNum(); //遍歷獲取單元格里的信息 for (int i = first; i <last; i++) { HSSFRow row=hs.getRow(i); int firstCellNum=row.getFirstCellNum();//獲取所在行的第一個行號 int lastCellNum=row.getLastCellNum();//獲取所在行的最后一個行號 for (int j = firstCellNum; j <lastCellNum; j++) { HSSFCell cell=row.getCell(j); String value=cell.getStringCellValue(); System.out.print(value+' '); } System.out.println(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}

如果Excel版本過高則需要改寫用XSSF

public class PoiExpExcel2 { /** * POI生成Excel文件 * @author David * @param args */ public static void main(String[] args) { String[] title = {'id','name','sex'}; //創建Excel工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); //創建一個工作表sheet Sheet sheet = workbook.createSheet(); //創建第一行 Row row = sheet.createRow(0); Cell cell = null; //插入第一行數據 id,name,sex for (int i = 0; i < title.length; i++) { cell = row.createCell(i); cell.setCellValue(title[i]); } //追加數據 for (int i = 1; i <= 10; i++) { Row nextrow = sheet.createRow(i); Cell cell2 = nextrow.createCell(0); cell2.setCellValue('a' + i); cell2 = nextrow.createCell(1); cell2.setCellValue('user' + i); cell2 = nextrow.createCell(2); cell2.setCellValue('男'); } //創建一個文件 File file = new File('e:/poi_test.xlsx'); try { file.createNewFile(); //將Excel內容存盤 FileOutputStream stream = FileUtils.openOutputStream(file); workbook.write(stream); stream.close(); } catch (IOException e) { e.printStackTrace(); } } }

四.定制導入模板

1.首先準備好模板的.xml文件,然后導入所需的jar包

例子:student.xml文件

<?xml version='1.0' encoding='UTF-8'?><excel code='student' name='學生信息導入'> <colgroup> <col index='A' width=’17em’></col> <col index='B' width=’17em’></col> <col index='C' width=’17em’></col> <col index='D' width=’17em’></col> <col index='E' width=’17em’></col> <col index='F' width=’17em’></col> </colgroup> <title> <tr height='16px'> <td rowspan='1' colspan='6' value='學生信息導入' /> </tr> </title> <thead> <tr height='16px'> <th value='編號' /> <th value='姓名' /> <th value='年齡' /> <th value='性別' /> <th value='出生日期' /> <th value=' 愛好' /> </tr> </thead> <tbody> <tr firstrow='2' firstcol='0' repeat='5'> <td type='string' isnullable='false' maxlength='30' /><!--用戶編號 --> <td type='string' isnullable='false' maxlength='50' /><!--姓名 --> <td type='numeric' format='##0' isnullable='false' /><!--年齡 --> <td type='enum' format='男,女' isnullable='true' /><!--性別 --> <td type='date' isnullable='false' maxlength='30' /><!--出生日期 --> <td type='enum' format='足球,籃球,乒乓球' isnullable='true' /><!--愛好 --> </tr> </tbody></excel>

所需jar包:commons-lang3-3.1.jarjdom.jarpoi-3.11-20141221.jarcommons-io-2.2.jar

java代碼:

//準備工作:導入相關jar包commons-lang3-3.1.jar,jdom.jar,poi-3.11-20141221.jarpublic class CreateTemp {public static void main(String[] args) { //獲取解析Xml路徑 String path=System.getProperty('user.dir')+'/student.xml'; File file=new File(path); SAXBuilder builder=new SAXBuilder(); //解析xml文件 try { Document document=builder.build(file); //創建Excel HSSFWorkbook workbook=new HSSFWorkbook(); //創建表格 HSSFSheet sheet=workbook.createSheet('sheet0'); //獲取Xml文件的根節點 Element root=document.getRootElement(); //獲取模板名稱 String tempName=root.getAttributeValue('name'); //設置列寬 Element colgroup=root.getChild('colgroup'); setColumnWidth(sheet,colgroup); //設置標題 int rownum = 0; int column = 0; Element title=root.getChild('title'); List<Element> trs=title.getChildren('tr'); for (int i = 0; i <trs.size(); i++) { Element tr=trs.get(i); List<Element> tds=tr.getChildren('td'); HSSFRow row=sheet.createRow(rownum); HSSFCellStyle cellStyle=workbook.createCellStyle();//創建單元格格式 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//標題居中 for (int j = 0; j < tds.size(); j++) { Element td=tds.get(j); HSSFCell cell=row.createCell(j); Attribute rowspan=td.getAttribute('rowspan'); Attribute colspan=td.getAttribute('colspan'); Attribute value=td.getAttribute('value'); if (value!=null) { String content=value.getValue(); cell.setCellValue(content); int rspan=rowspan.getIntValue()-1; int cspan=colspan.getIntValue()-1; //設置字體 HSSFFont font=workbook.createFont(); font.setFontName('仿宋_GB2312'); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字體加粗// font.setFontHeight((short)12); font.setFontHeightInPoints((short)12); cellStyle.setFont(font); cell.setCellStyle(cellStyle); //合并單元格居中 sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan)); } } rownum++; } //設置表頭 Element thead=root.getChild('thead'); trs=thead.getChildren('tr'); for (int i = 0; i < trs.size(); i++) { Element tr=trs.get(i); HSSFRow row=sheet.createRow(rownum); List<Element> ths=tr.getChildren('th'); for (int j = 0; j <ths.size(); j++) { Element th=ths.get(j); HSSFCell cell=row.createCell(j); Attribute value=th.getAttribute('value'); if (value!=null) { String content=value.getValue(); cell.setCellValue(content); } } rownum++; } //設置數據區域樣式 Element tbody = root.getChild('tbody'); Element tr=tbody.getChild('tr'); int repeat=tr.getAttribute('repeat').getIntValue(); List<Element> tds=tr.getChildren('td'); for (int i = 0; i < repeat; i++) { HSSFRow row=sheet.createRow(rownum); for (int j = 0; j < tds.size(); j++) { Element td=tds.get(j); HSSFCell cell=row.createCell(j); setType(workbook,cell,td); } } rownum++; //生成Excel導入模板 File tempFile=new File('e:/'+tempName+'.xls'); tempFile.delete(); tempFile.createNewFile(); FileOutputStream fos=FileUtils.openOutputStream(tempFile); workbook.write(fos); fos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }} private static void setType(HSSFWorkbook workbook, HSSFCell cell, Element td) { Attribute typeAttr = td.getAttribute('type'); String type = typeAttr.getValue(); HSSFDataFormat format = workbook.createDataFormat(); HSSFCellStyle cellStyle = workbook.createCellStyle(); if('NUMERIC'.equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); Attribute formatAttr = td.getAttribute('format'); String formatValue = formatAttr.getValue(); formatValue = StringUtils.isNotBlank(formatValue)? formatValue : '#,##0.00'; cellStyle.setDataFormat(format.getFormat(formatValue)); }else if('STRING'.equalsIgnoreCase(type)){ cell.setCellValue(''); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellStyle.setDataFormat(format.getFormat('@')); }else if('DATE'.equalsIgnoreCase(type)){ cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cellStyle.setDataFormat(format.getFormat('yyyy-m-d')); }else if('ENUM'.equalsIgnoreCase(type)){ CellRangeAddressList regions = new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute('format'); String enumValue = enumAttr.getValue(); //加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(enumValue.split(',')); //數據有效性對象 HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint); workbook.getSheetAt(0).addValidationData(dataValidation); } cell.setCellStyle(cellStyle); } private static void setColumnWidth(HSSFSheet sheet, Element colgroup) { List<Element> cols=colgroup.getChildren('col');//獲取col的節點 for (int i = 0; i < cols.size(); i++) { Element col=cols.get(i); Attribute width=col.getAttribute('width');//獲取每列中的width屬性 String unit = width.getValue().replaceAll('[0-9,.]', '');//單位 String value = width.getValue().replaceAll(unit, '');//數值 int v=0; if(StringUtils.isBlank(unit) || 'px'.endsWith(unit)){ v = Math.round(Float.parseFloat(value) * 37F); }else if ('em'.endsWith(unit)){ v = Math.round(Float.parseFloat(value) * 267.5F); }//對單位進行判斷 sheet.setColumnWidth(i, v); } }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: excel
相關文章:
主站蜘蛛池模板: 英国公司注册-新加坡公司注册-香港公司开户-离岸公司账户-杭州商标注册-杭州优创企业 | GEDORE扭力螺丝刀-GORDON防静电刷-CHEMTRONICS吸锡线-上海卓君电子有限公司 | 玉米深加工机械,玉米加工设备,玉米加工机械等玉米深加工设备制造商-河南成立粮油机械有限公司 | 高速混合机_锂电混合机_VC高效混合机-无锡鑫海干燥粉体设备有限公司 | 地磅-电子地磅维修-电子吊秤-汽车衡-无人值守系统-公路治超-鹰牌衡器 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 快速门厂家批发_PVC快速卷帘门_高速门_高速卷帘门-广州万盛门业 快干水泥|桥梁伸缩缝止水胶|伸缩缝装置生产厂家-广东广航交通科技有限公司 | 胜为光纤光缆_光纤跳线_单模尾纤_光纤收发器_ODF光纤配线架厂家直销_北京睿创胜为科技有限公司 - 北京睿创胜为科技有限公司 | 百度关键词优化_网站优化_SEO价格 - 云无限好排名 | 海外整合营销-独立站营销-社交媒体运营_广州甲壳虫跨境网络服务 焊管生产线_焊管机组_轧辊模具_焊管设备_焊管设备厂家_石家庄翔昱机械 | 贵阳用友软件,贵州财务软件,贵阳ERP软件_贵州优智信息技术有限公司 | 深圳标识制作公司-标识标牌厂家-深圳广告标识制作-玟璟广告-深圳市玟璟广告有限公司 | 骁龙云呼电销防封号系统-axb电销平台-外呼稳定『免费试用』 | 电主轴-高速精密电主轴-高速电机厂家-瑞德沃斯品牌有限公司 | 【官网】博莱特空压机,永磁变频空压机,螺杆空压机-欧能优 | 河南档案架,档案密集架,手动密集架,河南密集架批发/报价 | 沈阳液压泵_沈阳液压阀_沈阳液压站-沈阳海德太科液压设备有限公司 | 原子吸收设备-国产分光光度计-光谱分光光度计-上海光谱仪器有限公司 | 密集柜_档案密集柜_智能密集架_密集柜厂家_密集架价格-智英伟业 密集架-密集柜厂家-智能档案密集架-自动选层柜订做-河北风顺金属制品有限公司 | 长沙中央空调维修,中央空调清洗维保,空气能热水工程,价格,公司就找维小保-湖南维小保环保科技有限公司 | 纯水设备_苏州皙全超纯水设备水处理设备生产厂家 | 中高频感应加热设备|高频淬火设备|超音频感应加热电源|不锈钢管光亮退火机|真空管烤消设备 - 郑州蓝硕工业炉设备有限公司 | 红立方品牌应急包/急救包加盟,小成本好项目代理_应急/消防/户外用品加盟_应急好项目加盟_新奇特项目招商 - 中红方宁(北京) 供应链有限公司 | 广州活动策划公司-15+年专业大型公关活动策划执行管理经验-睿阳广告 | 期货软件-专业期货分析软件下载-云智赢 | 环氧乙烷灭菌器_压力蒸汽灭菌器_低温等离子过氧化氢灭菌器 _低温蒸汽甲醛灭菌器_清洗工作站_医用干燥柜_灭菌耗材-环氧乙烷灭菌器_脉动真空压力蒸汽灭菌器_低温等离子灭菌设备_河南省三强医疗器械有限责任公司 | 成都离婚律师|成都结婚律师|成都离婚财产分割律师|成都律师-成都离婚律师网 | 森旺-A级防火板_石英纤维板_不燃抗菌板装饰板_医疗板 | Maneurop/美优乐压缩机,活塞压缩机,型号规格,技术参数,尺寸图片,价格经销商 | 餐饮小吃技术培训-火锅串串香培训「何小胖培训」_成都点石成金[官网] | 德国EA可编程直流电源_电子负载,中国台湾固纬直流电源_交流电源-苏州展文电子科技有限公司 | 水性漆|墙面漆|木器家具漆|水漆涂料_晨阳水漆官网 | 北京网站建设-企业网站建设-建站公司-做网站-北京良言多米网络公司 | 聚丙烯酰胺PAM-聚合氯化铝PAC-絮凝剂-河南博旭环保科技有限公司 巨野电机维修-水泵维修-巨野县飞宇机电维修有限公司 | 点焊机-缝焊机-闪光对焊机-电阻焊设备生产厂家-上海骏腾发智能设备有限公司 | 计算机毕业设计源码网| 空调风机,低噪声离心式通风机,不锈钢防爆风机,前倾皮带传动风机,后倾空调风机-山东捷风风机有限公司 | 精密线材测试仪-电线电缆检测仪-苏州欣硕电子科技有限公司 | 艺术涂料_进口艺术涂料_艺术涂料加盟_艺术涂料十大品牌 -英国蒙太奇艺术涂料 | 电动高尔夫球车|电动观光车|电动巡逻车|电动越野车厂家-绿友机械集团股份有限公司 | 防火卷帘门价格-聊城一维工贸特级防火卷帘门厂家▲ |