java生成excel文件|java代码怎么导出excel文件

java生成excel文件|java代码怎么导出excel文件的第1张示图

❶ 关于用java创建Excel文件

可以运行成功,估计是你没有导入jxl.jar包

如果是javaProject

工程名—>右键properties–>javaBuildPath配置Libraries

如果是j2eeweb工程,则可直接将jar包拷贝到wEB-INF下的lib目录中,会自动加载到classpath

❷ java代码怎么导出excel文件

excel工具类package com.ohd.ie.proct.action;import java.awt.image.BufferedImage;import java.io.*;import javax.imageio.ImageIO;import org.apache.commons.io.output.ByteArrayOutputStream;import jxl.Workbook;import jxl.format.Alignment;import jxl.format.VerticalAlignment;import jxl.write.*;import jxl.write.Number;import jxl.write.biff.RowsExceededException;public class Excel {private OutputStream os;private WritableWorkbook wwb = null;private WritableSheet ws = null;private WritableCellFormat titleCellFormat = null;private WritableCellFormat noBorderCellFormat = null;private WritableCellFormat hasBorderCellFormat = null;private WritableCellFormat hasBorderCellNumberFormat = null;private WritableCellFormat hasBorderCellNumberFormat2 = null;private WritableImage writableImage=null;private int r;public Excel(OutputStream os){this.os = os;r = -1;try {wwb = Workbook.createWorkbook(os);//创建工作表ws = wwb.createSheet("sheet1",0);//设置表头字体,大小,加粗titleCellFormat = new WritableCellFormat();titleCellFormat.setAlignment(Alignment.CENTRE);titleCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);//自动换行titleCellFormat.setWrap(true);titleCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12,WritableFont.BOLD));titleCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);//设置表格字体,大小—-无边框noBorderCellFormat = new WritableCellFormat();noBorderCellFormat.setAlignment(Alignment.CENTRE);noBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);noBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));//设置表格字体,大小—-有边框hasBorderCellFormat = new WritableCellFormat();hasBorderCellFormat.setAlignment(Alignment.CENTRE);hasBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);hasBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));hasBorderCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);//设置表格字体,大小—-有边框(小数)NumberFormat nf = new NumberFormat("#0.00");hasBorderCellNumberFormat = new WritableCellFormat(nf);hasBorderCellNumberFormat.setAlignment(Alignment.CENTRE);hasBorderCellNumberFormat.setVerticalAlignment(VerticalAlignment.CENTRE);hasBorderCellNumberFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));hasBorderCellNumberFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);//设置表格字体,大小—-有边框(整数)NumberFormat nf2 = new NumberFormat("#0");hasBorderCellNumberFormat2 = new WritableCellFormat(nf2);hasBorderCellNumberFormat2.setAlignment(Alignment.CENTRE);hasBorderCellNumberFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);hasBorderCellNumberFormat2.setFont(new WritableFont(WritableFont.createFont("宋体"),12));hasBorderCellNumberFormat2.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/**** @param content 内容* @param c 列* @param style 样式* @param isNewLine 是否换行* @param mergeType 合并类型* @param mergeCount 合并个数* @param width 单元格宽*/public void setExcelCell(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width){try {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////报表内容////////////////////////////////////////////////////////////////////////////////////////////////////////////////////if(isNewLine){r++;}WritableCell l = null;if(style == 1){l = new Label(c,r,content,titleCellFormat);}else if(style == 2){l = new Label(c,r,content,noBorderCellFormat);}else if(style == 3){l = new Label(c,r,content,hasBorderCellFormat);}else if(style == 4){l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);}else if(style == 5){l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);}ws.addCell(l);if(width != 0){ws.setColumnView(c,width);}//veryhuo,comif(mergeType == 1){//x 轴方向ws.mergeCells(c, r, c+mergeCount-1 , r);}else if(mergeType == 2){//y 轴方向ws.mergeCells(c, r, c, r+mergeCount-1);}if(isNewLine){ws.setRowView(r, 350);if(style == 1 && r != 0){ws.setRowView(r, 900);}else{ws.setRowView(r, 350);}}//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////} catch (Exception e) {System.out.println(e.toString());}}public void setExcelCellEx(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width,int row){try {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////报表内容////////////////////////////////////////////////////////////////////////////////////////////////////////////////////if(isNewLine){r++;}WritableCell l = null;if(style == 1){l = new Label(c,r,content,titleCellFormat);}else if(style == 2){l = new Label(c,r,content,noBorderCellFormat);}else if(style == 3){if(content.indexOf(".jpg")!=-1 ||content.indexOf(".JPG")!=-1){File outputFile=null;File imgFile =new File(content);if(imgFile.exists()&&imgFile.length()>0){BufferedImage input=null;try {input = ImageIO.read(imgFile);} catch (Exception e) {e.printStackTrace();}if(input!=null){String path=imgFile.getAbsolutePath();outputFile = new File(path.substring(0,path.lastIndexOf('.')+1)+"png");ImageIO.write(input, "PNG", outputFile);if(outputFile.exists()&&outputFile.length()>0){ws.setRowView(row,2000);//ws.setColumnView(8, 10);writableImage = new WritableImage(c+0.1, row+0.1, 0.8, 0.8, outputFile);ws.addImage(writableImage);l = new Label(c,r,"",hasBorderCellFormat);}}}}else{l = new Label(c,r,content,hasBorderCellFormat);}}else if(style == 4){l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);}else if(style == 5){l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);}ws.addCell(l);if(width != 0){ws.setColumnView(c,width);}if(mergeType == 1){//x 轴方向ws.mergeCells(c, r, c+mergeCount-1 , r);}else if(mergeType == 2){//y 轴方向ws.mergeCells(c, r, c, r+mergeCount-1);}if(isNewLine){ws.setRowView(r, 350);if(style == 1 && r != 0){ws.setRowView(r, 900);}else{ws.setRowView(r, 350);}}} catch (Exception e) {System.out.println(e.toString());}}public void setRowHeight(int val){try {ws.setRowView(r, val);} catch (RowsExceededException e) {e.printStackTrace();}}public void getExcelResult(){try {wwb.write();} catch (Exception e) {System.out.println(e.toString());}finally{if(wwb != null){try {wwb.close();if(os != null){os.close();}} catch (WriteException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}}}需要的jar包:jxl.jar

❸ java怎么导出excel表格

通过这个例子,演示以下如何用java生成excel文件:import org.apache.poi.hssf.usermodel.*;import java.io.FileOutputStream;import java.io.IOException;publicclass CreateCells{publicstaticvoid main(String[] args)throws IOException{HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet对象// Create a row and put some cells in it. Rows are 0 based.HSSFRow row = sheet.createRow((short)0);//建立新行// Create a cell and put a value in it.HSSFCell cell = row.createCell((short)0);//建立新cellcell.setCellValue(1);//设置cell的整数类型的值// Or do it on one line.row.createCell((short)1).setCellValue(1.2);//设置cell浮点类型的值row.createCell((short)2).setCellValue("test");//设置cell字符类型的值row.createCell((short)3).setCellValue(true);//设置cell布尔类型的值HSSFCellStyle cellStyle = wb.createCellStyle();//建立新的cell样式cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"));//设置cell样式为定制的日期格式HSSFCell dCell =row.createCell((short)4);dCell.setCellValue(new Date());//设置cell为日期类型的值dCell.setCellStyle(cellStyle); //设置该cell日期的显示格式HSSFCell csCell =row.createCell((short)5);csCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断csCell.setCellValue("中文测试_Chinese words Test");//设置中西文结合字符串row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);//建立错误cell// Write the output to a fileFileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();}}

❹ 如何用java代码将数据库中的数据生成excel表

java 读excel 还是比较方便简单的,原理就是,先用java 读取excel,然后,一行行的写入数据库,字段的话,你自己程序里面写就行了,给你个例子:从Excel读取数据,生成新的Excel,以及修改Excelpackage common.util;import jxl.*;import jxl.format.UnderlineStyle;import jxl.write.*;import jxl.write.Number;import jxl.write.Boolean;import java.io.*;/** * Created by IntelliJ IDEA. * User: xl * Date: 2005-7-17 * Time: 9:33:22 * To change this template use File | Settings | File Templates. */public class ExcelHandle{ public ExcelHandle() { } /** * 读取Excel * * @param filePath */ public static void readExcel(String filePath) { try { InputStream is = new FileInputStream(filePath); Workbook rwb = Workbook.getWorkbook(is); //Sheet st = rwb.getSheet("0")这里有两种方法获取sheet表,1为名字,而为下标,从0开始 Sheet st = rwb.getSheet("original"); Cell c00 = st.getCell(0,0); //通用的获取cell值的方式,返回字符串 String strc00 = c00.getContents(); //获得cell具体类型值的方式 if(c00.getType() == CellType.LABEL) { LabelCell labelc00 = (LabelCell)c00; strc00 = labelc00.getString(); } //输出 System.out.println(strc00); //关闭 rwb.close(); } catch(Exception e) { e.printStackTrace(); } } /** * 输出Excel * * @param os */ public static void writeExcel(OutputStream os) { try { /** * 只能通过API提供的工厂方法来创建Workbook,而不能使用WritableWorkbook的构造函数, * 因为类WritableWorkbook的构造函数为protected类型 * method(1)直接从目标文件中读取WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile)); * method(2)如下实例所示 将WritableWorkbook直接写入到输出流 */ WritableWorkbook wwb = Workbook.createWorkbook(os); //创建Excel工作表 指定名称和位置 WritableSheet ws = wwb.createSheet("Test Sheet 1",0); //**************往工作表中添加数据***************** //1.添加Label对象 Label label = new Label(0,0,"this is a label test"); ws.addCell(label); //添加带有字型Formatting对象 WritableFont wf = new WritableFont(WritableFont.TIMES,18,WritableFont.BOLD,true); WritableCellFormat wcf = new WritableCellFormat(wf); Label labelcf = new Label(1,0,"this is a label test",wcf); ws.addCell(labelcf); //添加带有字体颜色的Formatting对象 WritableFont wfc = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED); WritableCellFormat wcfFC = new WritableCellFormat(wfc); Label labelCF = new Label(1,0,"This is a Label Cell",wcfFC); ws.addCell(labelCF); //2.添加Number对象 Number labelN = new Number(0,1,3.1415926); ws.addCell(labelN); //添加带有formatting的Number对象 NumberFormat nf = new NumberFormat("#.##"); WritableCellFormat wcfN = new WritableCellFormat(nf); Number labelNF = new jxl.write.Number(1,1,3.1415926,wcfN); ws.addCell(labelNF); //3.添加Boolean对象 Boolean labelB = new jxl.write.Boolean(0,2,false); ws.addCell(labelB); //4.添加DateTime对象 jxl.write.DateTime labelDT = new jxl.write.DateTime(0,3,new java.util.Date()); ws.addCell(labelDT); //添加带有formatting的DateFormat对象 DateFormat df = new DateFormat("dd MM yyyy hh:mm:ss"); WritableCellFormat wcfDF = new WritableCellFormat(df); DateTime labelDTF = new DateTime(1,3,new java.util.Date(),wcfDF); ws.addCell(labelDTF); //添加图片对象,jxl只支持png格式图片 File image = new File("f:\\2.png"); WritableImage wimage = new WritableImage(0,1,2,2,image); ws.addImage(wimage); //写入工作表 wwb.write(); wwb.close(); } catch(Exception e) { e.printStackTrace(); } } /** * 拷贝后,进行修改,其中file1为被对象,file2为修改后创建的对象 * 尽单元格原有的格式化修饰是不能去掉的,我们还是可以将新的单元格修饰加上去, * 以使单元格的内容以不同的形式表现 * @param file1 * @param file2 */ public static void modifyExcel(File file1,File file2) { try { Workbook rwb = Workbook.getWorkbook(file1); WritableWorkbook wwb = Workbook.createWorkbook(file2,rwb);// WritableSheet ws = wwb.getSheet(0); WritableCell wc = ws.getWritableCell(0,0); //判断单元格的类型,做出相应的转换 if(wc.getType == CellType.LABEL) { Label label = (Label)wc; label.setString("The value has been modified"); } wwb.write(); wwb.close(); rwb.close(); } catch(Exception e) { e.printStackTrace(); } } //测试 public static void main(String[] args) { try { //读Excel ExcelHandle.readExcel("f:/testRead.xls"); //输出Excel File fileWrite = new File("f:/testWrite.xls"); fileWrite.createNewFile(); OutputStream os = new FileOutputStream(fileWrite); ExcelHandle.writeExcel(os); //修改Excel ExcelHandle.modifyExcel(new file(""),new File("")); } catch(Exception e) { e.printStackTrace(); } }}2.在jsp中做相关测试,创建一个writeExcel.jsp<%response.reset();//清除Bufferresponse.setContentType("application/vnd.ms-excel");File fileWrite = new File("f:/testWrite.xls");fileWrite.createNewFile();new FileOutputStream(fileWrite);ExcelHandle.writeExcel(new FileOutputStream(fileWrite));%>在IE中浏览writeExcel.jsp就可以动态生成Excel文档了,其中response.setContentType("application/vnd.ms- excel");语句必须要,才能确保不乱码,在jsp中输入<%@page contentType="application/vnd.ms- excel;charset=GBK"%>不行。

❺ java如何生成excel,具体的

poi或jxl都行你从网上下载个jxl.jar的jar包简单说一下jxl导出excel过程//先创建一个excel文件String excelPath = "D:\\系统用户.xls";File excelFile = new File(excelPath);if (!excelFile.exists()) {excelFile.createNewFile();}WritableWorkbook book = Workbook.createWorkbook(excelFile);WritableSheet ws = book.createSheet("用户信息", 0); //新建一个sheet—————//往表中添加内容ws.addCell(WritableCell )————//将数据写入所建的excelbook.write();book.close();

❻ java怎么生成EXCEL文件

可以使用apache的poi包,这是一个开源项目,可方便读写excel文件,这里有一些例子:http://dev.csdn.net/develop/article/73/73804.shtmhttp://www.chinahtm.cn/program/26385.html

❼ 利用java怎么实现生成报表(Excel文件)

JAVA POI组件//创建HSSFWorkbook对象HSSFWorkbookwb=newHSSFWorkbook();//创建HSSFSheet对象HSSFSheetsheet=wb.createSheet("sheet0");//创建HSSFRow对象HSSFRowrow=sheet.createRow((short)0);//创建HSSFCell对象HSSFCellcell=row.createCell((short)0);//用来处理中文问题cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置单元格的值cell.setCellValue("单元格中的中文");//定义你需要的输出流OutputStreamout=newFileOutputStream("viwo.xls");//输出Excel

❽ java如何输出xls格式的Excel表格文件

有个开源的东东-jxl.jar,可以到http://sourceforge.net/project/showfiles.php?group_id=79926下载。一.读取Excel文件内容 /**读取Excel文件的内容 * @param file 待读取的文件 * @return */ public static String readExcel(File file){ StringBuffer sb = new StringBuffer(); Workbook wb = null; try { //构造Workbook(工作薄)对象 wb=Workbook.getWorkbook(file); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(wb==null) return null; //获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了 Sheet[] sheet = wb.getSheets(); if(sheet!=null&&sheet.length>0){ //对每个工作表进行循环 for(int i=0;i<sheet.length;i++){ //得到当前工作表的行数 int rowNum = sheet[i].getRows(); for(int j=0;j<rowNum;j++){ //得到当前行的所有单元格 Cell[] cells = sheet[i].getRow(j); if(cells!=null&&cells.length>0){ //对每个单元格进行循环 for(int k=0;k<cells.length;k++){ //读取当前单元格的值 String cellValue = cells[k].getContents(); sb.append(cellValue+" "); } } sb.append(" "); } sb.append(" "); } } //最后关闭资源,释放内存 wb.close(); return sb.toString(); }二.写入Excel文件这里有很多格式了,比如文本内容加粗,加上某些颜色等,可以参考jxl的api,同时还推荐一篇不错的文章:http://www.ibm.com/developerworks/cn/java/l-javaExcel/?ca=j-t10 /**生成一个Excel文件 * @param fileName 要生成的Excel文件名 */ public static void writeExcel(String fileName){ WritableWorkbook wwb = null; try { //首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象 wwb = Workbook.createWorkbook(new File(fileName)); } catch (IOException e) { e.printStackTrace(); } if(wwb!=null){ //创建一个可写入的工作表 //Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置 WritableSheet ws = wwb.createSheet("sheet1", 0); //下面开始添加单元格 for(int i=0;i<10;i++){ for(int j=0;j<5;j++){ //这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行 Label labelC = new Label(j, i, "这是第"+(i+1)+"行,第"+(j+1)+"列"); try { //将生成的单元格添加到工作表中 ws.addCell(labelC); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } } try { //从内存中写入文件中 wwb.write(); //关闭资源,释放内存 wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } } 三.在一个Excel文件中查找是否包含某一个关键字 /**搜索某一个文件中是否包含某个关键字 * @param file 待搜索的文件 * @param keyWord 要搜索的关键字 * @return */ public static boolean searchKeyWord(File file,String keyWord){ boolean res = false; Workbook wb = null; try { //构造Workbook(工作薄)对象 wb=Workbook.getWorkbook(file); } catch (BiffException e) { return res; } catch (IOException e) { return res; } if(wb==null) return res; //获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了 Sheet[] sheet = wb.getSheets(); boolean breakSheet = false; if(sheet!=null&&sheet.length>0){ //对每个工作表进行循环 for(int i=0;i<sheet.length;i++){ if(breakSheet) break; //得到当前工作表的行数 int rowNum = sheet[i].getRows(); boolean breakRow = false; for(int j=0;j<rowNum;j++){ if(breakRow) break; //得到当前行的所有单元格 Cell[] cells = sheet[i].getRow(j); if(cells!=null&&cells.length>0){ boolean breakCell = false; //对每个单元格进行循环 for(int k=0;k<cells.length;k++){ if(breakCell) break; //读取当前单元格的值 String cellValue = cells[k].getContents(); if(cellValue==null) continue; if(cellValue.contains(keyWord)){ res = true; breakCell = true; breakRow = true; breakSheet = true; } } } } } } //最后关闭资源,释放内存 wb.close(); return res; } 四.往Excel中插入图片图标插入图片的实现很容易,参看以下代码: /**往Excel中插入图片 * @param dataSheet 待插入的工作表 * @param col 图片从该列开始 * @param row 图片从该行开始 * @param width 图片所占的列数 * @param height 图片所占的行数 * @param imgFile 要插入的图片文件 */ public static void insertImg(WritableSheet dataSheet, int col, int row, int width, int height, File imgFile){ WritableImage img = new WritableImage(col, row, width, height, imgFile); dataSheet.addImage(img); } 以上代码的注释已经很清楚了,大概也就不用再解释了,我们可以用如下程序验证: try { //创建一个工作薄 WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls")); //待插入的工作表 WritableSheet imgSheet = workbook.createSheet("Images",0); //要插入的图片文件 File imgFile = new File("D:/1.png"); //图片插入到第二行第一个单元格,长宽各占六个单元格 insertImg(imgSheet,0,1,6,6,imgFile); workbook.write(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); }但是jxl只支持png格式的图片,jpg格式和gif格式都不支持五.插入页眉页脚一般的页眉页脚都分为三个部分,左,中,右三部分,利用如下代码可实现插入页眉页脚 /**向Excel中加入页眉页脚 * @param dataSheet 待加入页眉的工作表 * @param left * @param center * @param right */ public static void setHeader(WritableSheet dataSheet,String left,String center,String right){ HeaderFooter hf = new HeaderFooter(); hf.getLeft().append(left); hf.getCentre().append(center); hf.getRight().append(right); //加入页眉 dataSheet.getSettings().setHeader(hf); //加入页脚 //dataSheet.getSettings().setFooter(hf); }我们可以用如下代码测试该方法: try { //创建一个工作薄 WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls")); //待插入的工作表 WritableSheet dataSheet = workbook.createSheet("加入页眉",0); ExcelUtils.setHeader(dataSheet, "chb", "2007-03-06", "第1页,共3页"); workbook.write(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); }六偷懒工具设计之sql2Excel今天在公司陪山东客户调试,远程登录,我在linux下什么工具都没有,用ssh登录服务器,直接用mysql查询数据库,提出记录中的所有汉字全是乱码。哎,可恶的公司,不让我用windows,要不我就可以用putty或者EMS了,我ft! 甚是不爽之下,我决定自己写个工具了,把客户数据库中的数据全部提取并保存到Excel中,这样我不就可以一目了然了嘛,嘿嘿,好吧,那我就写一个工具吧。第一部分就是谁都会的jdbc操作,连接数据库,提取数据集合。 Connection con; Statement state; /**初始化连接 * @param serverIp * @param dataBase * @param userName * @param password * @throws ClassNotFoundException * @throws SQLException */ public void init(String serverIp,String dataBase,String userName,String password) throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver"); //配置数据源 String url="jdbc:mysql://"+serverIp+"/"+dataBase+"?useUnicode=true&characterEncoding=GB2312"; con=DriverManager.getConnection(url,userName,password); } /**得到查询结果集 * @param sql * @return * @throws SQLException */ public ResultSet getResultSet(String sql) throws SQLException{ state = con.createStatement(); ResultSet res = state.executeQuery(sql); return res; } /**关闭连接 * @throws SQLException */ public void close() throws SQLException{ if(con!=null) con.close(); if(state!=null) state.close(); }第二部分就是把ResultSet中的记录写入一个Excel文件操作Excel,我用的是jxl,不熟的同学可以参考:利用java操作Excel文件 /**将查询结果写入Excel文件中 * @param rs * @param file * @throws SQLException */ public void writeExcel(ResultSet rs,File file) throws SQLException{ WritableWorkbook wwb = null; try{ //首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象 wwb = Workbook.createWorkbook(file); } catch (IOException e){ e.printStackTrace(); } if(wwb!=null){ WritableSheet ws = wwb.createSheet("sheet1", 0); int i=0; while(rs.next()){ Label label1 = new Label(0, i, rs.getString("id")); Label label2 = new Label(1, i, rs.getString("category")); try { ws.addCell(label1); ws.addCell(label2); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } i++; } try { //从内存中写入文件中 wwb.write(); //关闭资源,释放内存 wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e){ e.printStackTrace(); } } }测试程序: Sql2Excel se = new Sql2Excel(); try { se.init("127.0.0.1","mydabase", "root", "1234"); ResultSet rs = se.getResultSet("select id,category from xx "); se.writeExcel(rs, new File("/root/sql2excel.xls")); se.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }

❾ java代码创建一个Excel文件

importjava.io.File;publicclassTest{publicstaticvoidmain(String[]args)throwsException{Filef=newFile("d:/1.xls");f.createNewFile();}}

好吧,之前没看到“用poi”这句话。现在下面的是用poi的:

importjava.io.FileOutputStream;importjava.io.IOException;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;publicclassTest{publicstaticvoidmain(String[]args){try{HSSFWorkbookworkbook=newHSSFWorkbook();FileOutputStreamfileOut=newFileOutputStream("D:/2.xls");workbook.write(fileOut);fileOut.close();}catch(IOExceptione){e.printStackTrace();}}}

未经允许不得转载:山九号 » java生成excel文件|java代码怎么导出excel文件

赞 (0)