乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > 在Java编程中怎么将从数据库查询出来的数据导成Excel文...-java把数据导出excel表格,excel数据导出

在Java编程中怎么将从数据库查询出来的数据导成Excel文...-java把数据导出excel表格,excel数据导出

作者:乔山办公网日期:

返回目录:excel表格制作


前段时间正好做了,导入和导出的,你自己看吧
/**导出数据为XLS格式
* @param fos
* @param bo
*/
public void writeExcelBo(FileOutputStream fos, java.util.Vector ve)
{
jxl.write.WritableWorkbook wwb;
try
{
wwb= Workbook.createWorkbook(fos);
jxl.write.WritableSheet ws= wwb.createSheet("booksheet", 10);
ws.addCell(new jxl.write.Label(0, 1, "书目ID"));
ws.addCell(new jxl.write.Label(1, 1, "ISBN"));
ws.addCell(new jxl.write.Label(2, 1, "定价"));
ws.addCell(new jxl.write.Label(3, 1, "书名"));
ws.addCell(new jxl.write.Label(4, 1, "原书名"));
ws.addCell(new jxl.write.Label(5, 1, "副题名"));
ws.addCell(new jxl.write.Label(6, 1, "著者"));
ws.addCell(new jxl.write.Label(7, 1, "译者"));
ws.addCell(new jxl.write.Label(8, 1, "版次"));
ws.addCell(new jxl.write.Label(9, 1, "出版地"));
ws.addCell(new jxl.write.Label(10, 1, "出版社"));
ws.addCell(new jxl.write.Label(11, 1, "出版日期e799bee5baa6e79fa5e98193e78988e69d83366"));
ws.addCell(new jxl.write.Label(12, 1, "页数"));
ws.addCell(new jxl.write.Label(13, 1, "书高"));
ws.addCell(new jxl.write.Label(14, 1, "装帧"));
ws.addCell(new jxl.write.Label(15, 1, "丛书名"));
ws.addCell(new jxl.write.Label(16, 1, "一般性附注项"));
ws.addCell(new jxl.write.Label(17, 1, "简介"));
ws.addCell(new jxl.write.Label(18, 1, "主题词"));
ws.addCell(new jxl.write.Label(19, 1, "中图法分类"));
ws.addCell(new jxl.write.Label(20, 1, "更新日期"));
ws.addCell(new jxl.write.Label(21, 1, "本数"));
book=new Book[ve.size()];
for (int i= 0; i < ve.size(); i++)
{
book[i]= (Book)ve.get(i);
ws.addCell(new jxl.write.Label(0, i + 2, "" + book[i].getBookId()));
ws.addCell(new jxl.write.Label(1, i + 2, book[i].getIsbn()));
ws.addCell(new jxl.write.Label(2, i + 2, "" + book[i].getPrice()));
ws.addCell(new jxl.write.Label(3, i + 2, book[i].getBookTitle()));
ws.addCell(new jxl.write.Label(4, i + 2, book[i].getOldFilename()));
ws.addCell(new jxl.write.Label(5, i + 2, book[i].getSubTitle()));
ws.addCell(new jxl.write.Label(6, i + 2, book[i].getWriter()));
ws.addCell(new jxl.write.Label(7, i + 2, book[i].getTranscribe()));
ws.addCell(new jxl.write.Label(8, i + 2, "" + book[i].getVersion()));
ws.addCell(new jxl.write.Label(9, i + 2, book[i].getPublishCity()));
ws.addCell(new jxl.write.Label(10, i + 2, book[i].getPublisher()));
ws.addCell(new jxl.write.Label(11, i + 2, book[i].getPublishDate().toString()));
ws.addCell(new jxl.write.Label(12, i + 2, "" + book[i].getPage()));
ws.addCell(new jxl.write.Label(13, i + 2, "" + book[i].getHight()));
ws.addCell(new jxl.write.Label(14, i + 2, book[i].getInstall()));
ws.addCell(new jxl.write.Label(15, i + 2, book[i].getSeries()));
ws.addCell(new jxl.write.Label(16, i + 2, book[i].getNotes()));
ws.addCell(new jxl.write.Label(17, i + 2, book[i].getPrecisnotes()));
ws.addCell(new jxl.write.Label(18, i + 2, book[i].getSubject()));
ws.addCell(new jxl.write.Label(19, i + 2, book[i].getCls().replaceAll("_", "")));
ws.addCell(new jxl.write.Label(20, i + 2, book[i].getUpdatedate().toString()));
ws.addCell(new jxl.write.Label(21, i + 2, "0"));
}
jxl.write.WritableFont wfc=
new jxl.write.WritableFont(
WritableFont.ARIAL,
255,
WritableFont.BOLD,
false,
UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
jxl.write.WritableCellFormat wcfFC= new jxl.write.WritableCellFormat(wfc);
ws.addCell(new jxl.write.Label(0, 0, "为保证您提交定单的稳定和正确,导入定单时候请勿更改此表格式(请勿更改书目ID,订购本数自行添加!)"));
wwb.write();
//关闭Excel工作薄对象
wwb.close();
} catch (IOException e)
{} catch (RowsExceededException e)
{} catch (WriteException e)
{}
}

//导入EXCEL
if (f.getName().indexOf(".xls") > 0)
{
try
{
fis= new FileInputStream(f);
BookBean bob= new BookBean();
UserBean usb= new UserBean();
jxl.Workbook rwb= Workbook.getWorkbook(fis);
jxl.Sheet sh= rwb.getSheet(0);
int rowCount= sh.getRows();
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");
book= new Book[rowCount - 1];
for (int i= 1; i < rowCount; i++)
{
book[i - 1]= new Book();
jxl.Cell[] ce= sh.getRow(i);
book[i - 1].setIsbn(ce[0].getContents().toString());
book[i - 1].setSeries(ce[1].getContents().toString());
book[i - 1].setBookTitle(ce[2].getContents().toString());
book[i - 1].setWriter(ce[3].getContents().toString());
book[i - 1].setTranscribe(ce[4].getContents().toString());
book[i - 1].setPublisher(ce[5].getContents().toString());
book[i - 1].setPublishDate(sdf.parse(ce[6].getContents().toString(), new ParsePosition(0)));
book[i-1].setVersion(Integer.parseInt(ce[7].getContents().toString()));
book[i-1].setPage(Integer.parseInt(ce[8].getContents().toString()));
book[i-1].setCls(ce[9].getContents().toString());
book[i-1].setPrecisnotes(ce[10].getContents().toString());
book[i-1].setInstall(ce[11].getContents().toString());
book[i-1].setPrice(Float.parseFloat(ce[12].getContents().toString()));
book[i-1].setUserid(usb.getUser().getUserid());
getVector().addElement(book[i - 1]);
}
rwb.close();
fis.close();
} catch (FileNotFoundException e)
{} catch (BiffException e)
{} catch (IOException e)
{} catch (NumberFormatException e)
{
ShowMessage("数据导入失败,请按照本软件要求的EXCEL格式导入定单");
}
}

import jxl.*;
import jxl.write.*;
import java.io.*;
import java.io.File.*;
import java.util.*;

public class excel
{
public static void main(String[] args)
{

String targetfile = "c:/out.xls";//输出的excel文件名
String worksheet = "List";//输出的excel文件工作表名
String[] title = {"ID","NAME","DESCRIB"};//excel工作表的标题

WritableWorkbook workbook;
try
{
//创建可写入的Excel工作薄,运行生成的文件在tomcat/bin下
//workbook = Workbook.createWorkbook(new File("output.xls"));
System.out.println("begin");

OutputStream os=new FileOutputStream(targetfile);
workbook=Workbook.createWorkbook(os);

WritableSheet sheet = workbook.createSheet(worksheet, 0); //添加第一个工作表
//WritableSheet sheet1 = workbook.createSheet("MySheet1", 1); //可添加第二个工作
/*
jxl.write.Label label = new jxl.write.Label(0, 2, "A label record"); //put a label in cell A3, Label(column,row)
sheet.addCell(label);
*/

jxl.write.Label label;
for (int i=0; i<title.length; i++)
{
//Label(列号,行号 ,内容 )
label = new jxl.write.Label(i, 0, title[i]); //put the title in row1
sheet.addCell(label);
}

//下列添加的对字体等的设置均调试通过,可作参考用e79fa5e98193e78988e69d83337

//添加数字
jxl.write.Number number = new jxl.write.Number(3, 4, 3.14159); //put the number 3.14159 in cell D5
sheet.addCell(number);

//添加带有字型Formatting的对象
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES,10,WritableFont.BOLD,true);
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
jxl.write.Label labelCF = new jxl.write.Label(4,4,"文本",wcfF);
sheet.addCell(labelCF);

//添加带有字体颜色,带背景颜色 Formatting的对象
jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
wcfFC.setBackground(jxl.format.Colour.BLUE);
jxl.write.Label labelCFC = new jxl.write.Label(1,5,"带颜色",wcfFC);
sheet.addCell(labelCFC);

//添加带有formatting的Number对象
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
jxl.write.Number labelNF = new jxl.write.Number(1,1,3.1415926,wcfN);
sheet.addCell(labelNF);

//3.添加Boolean对象
jxl.write.Boolean labelB = new jxl.write.Boolean(0,2,false);
sheet.addCell(labelB);

//4.添加DateTime对象
jxl.write.DateTime labelDT = new jxl.write.DateTime(0,3,new java.util.Date());
sheet.addCell(labelDT);

//添加带有formatting的DateFormat对象
jxl.write.DateFormat df = new jxl.write.DateFormat("ddMMyyyyhh:mm:ss");
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(1,3,new java.util.Date(),wcfDF);
sheet.addCell(labelDTF);

//和宾单元格
//sheet.mergeCells(int col1,int row1,int col2,int row2);//左上角到右下角
sheet.mergeCells(4,5,8,10);//左上角到右下角
wfc = new jxl.write.WritableFont(WritableFont.ARIAL,40,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);
jxl.write.WritableCellFormat wchB = new jxl.write.WritableCellFormat(wfc);
wchB.setAlignment(jxl.format.Alignment.CENTRE);
labelCFC = new jxl.write.Label(4,5,"单元合并",wchB);
sheet.addCell(labelCFC); //

//设置边框
jxl.write.WritableCellFormat wcsB = new jxl.write.WritableCellFormat();
wcsB.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THICK);
labelCFC = new jxl.write.Label(0,6,"边框设置",wcsB);
sheet.addCell(labelCFC);
workbook.write();
workbook.close();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("end");
Runtime r=Runtime.getRuntime();
Process p=null;
//String cmd[]={"notepad","exec.java"};
String cmd[]={"C:\\Program Files\\Microsoft Office\\Office\\EXCEL.EXE","out.xls"};
try{
p=r.exec(cmd);
}
catch(Exception e){
System.out.println("error executing: "+cmd[0]);
}

}
}

导入数据库

	@RequestMapping("/uploadOrderFile")
@ResponseBody
public Object uploadOrderFile(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file") MultipartFile[] files) throws ServletException, IOException, ParseException{
Workbook rwb=null;
if(files!=null && files.length>0){
       try {
     // String filePath = request.getSession().getServletContext().getRealPath("/") + "\\uploadOrderFile\\" +  files.getOriginalFilename();
     // System.out.println("----------"+filePath);
     rwb = Workbook.getWorkbook(files[0].getInputStream());
     Sheet rs=rwb.getSheet(0);//默认0是第一张表,或者rwb.getSheet(Sheet1)Excel要导入的表名
     int clos=rs.getColumns();//得到所有的列
     int rows=rs.getRows();//得到所有的行
        //存放Excel表抬头名称以及对应的列
        Map<Integer,Object> map=new HashMap<Integer, Object>();
        //实体类集合存放每次循环获得的值
        List<Medicine> medicineList=new ArrayList<Medicine>();  
        for (int i = 0; i < rows; i++) {
          //创建实体类
        Medicine medicine=new Medicine();
         if(i==0){//遍历第一行获取抬头跟对应的列
          for (int j = 0; j <clos; j++) {//取得每个抬头名称对应的列           
          if(rs.getCell(j, i).getContents().equals("品名")){
          map.put(j,"品名");
          }else if(rs.getCell(j, i).getContents().equals("商品编号")){
          map.put(j,"商品编号");
          }else if(rs.getCell(j, i).getContents().equals("生产日期")){
          map.put(j,"生产日期");
          }else if(rs.getCell(j, i).getContents().equals("产地")){
          map.put(j,"产地");  
          }else if(rs.getCell(j, i).getContents().equals("生产厂家")){
          map.put(j,"生产厂家");
          }else if(rs.getCell(j, i).getContents().equals("批号")){
          map.put(j,"批号");
          }
          }
         }else{         
          //循环遍历map 》》》存的Excel表的抬头名称以及对应的列
          for (int j = 0; j < clos; j++) {
          if(map.get(j)==null){//如果=null 进入下一个循环
          continue;
          }
          if(map.get(j).equals("品名")){
          //如果为空结束当前循环,进入下一个循环
         if(rs.getCell(j, i).getContents()==null||rs.getCell(j, i).getContents().equals("")){
         continue;
         }           
          medicine.setMedicineName(rs.getCell(j, i).getContents());
          }else if(map.get(j).equals("商品编号")&&map.get(j)!=null){
          //如果为空结束当前循环,进入下一个循环
         if(rs.getCell(j, i).getContents()==null||rs.getCell(j, i).getContents().equals("")){
         continue;
         }  
          medicine.setMedicineCode(rs.getCell(j, i).getContents());           
          }else if(map.get(j).equals("生产日期")&&map.get(j)!=null){
          medicine.setCreateTime(rs.getCell(j, i).getContents());
          if(rs.getCell(j, i).getContents()!=null && !rs.getCell(j, i).getContents().equals("")){
          //如果生产日期存在 则+三年给到期日期赋值
          //CommonUtil.getMedicineEffectiveTime为封装好的类
          medicine.setEffectTime(CommonUtil.getMedicineEffectiveTime(rs.getCell(j, i).getContents(),3));
          }
          }else if(map.get(j).equals("产地")&&map.get(j)!=null){
          medicine.setAddress(rs.getCell(j, i).getContents());
          
          }else if(map.get(j).equals("生产厂家")&&map.get(j)!=null){
          medicine.setProducingArea(rs.getCell(j, i).getContents());
        
          }else if(map.get(j).equals("批号")&&map.get(j)!=null){
          medicine.setBatchNumber(rs.getCell(j, i).getContents());
          }         
          }
          medicineList.add(medicine);//获得的值放入集合中                    
         }         
        }
        //新增用到的list
        List<Medicine> addList=new ArrayList<Medicine>(); 
        //修改用到的list
        List<Medicine> updateList=new ArrayList<Medicine>(); 
        //导入数据
        for(int i=0;i<medicineList.size();i++){      
         //判断商品编号是否存在
         if(medicineService.selectMedicineCode(medicineList.get(i).getMedicineCode()).size()>0){
         //如果存在则修改         
         updateList.add(medicineList.get(i));        
         }else{         
         addList.add(medicineList.get(i));        
         }
      }
        int update=0;
        int add=0;
        if(updateList!=null&&updateList.size()>0){
         update=medicineService.updateMedicine(updateList);         
        }
        if(addList!=null&&addList.size()>0){
         add= medicineService.addMedicine(addList);        
        }
        if(update>0||add>0){
         return new ResponseModel().attr(ResponseModel.KEY_DATA,"数据导入成功!");
        }else{
         return new ResponseModel().attr(ResponseModel.KEY_ERROR,"数据导入失败!");
        }
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    
    }else{
     return new ResponseModel().attr(ResponseModel.KEY_ERROR,"没有需要导入的数据!");
    }
return null;
}

导出

package beans.excel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Boolean;
import jxl.write.DateFormats;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class MutiStyleExcelWrite {
    public void createExcel(OutputStream os) throws WriteException,IOException {
        //创建工作薄
        WritableWorkbook workbook = Workbook.createWorkbook(os);
        //创建新的一页
        WritableSheet sheet = workbook.createSheet("First Sheet", 0);
        //构造表头
        sheet.mergeCells(0, 0, 4, 0);//添加合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
        WritableFont bold = new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//设置字体种类和黑体显示,字体为Arial,字号大小为10,采用黑体显示
        WritableCellFormat titleFormate = new WritableCellFormat(bold);//生成一个单元格样式控制对象
        titleFormate.setAlignment(jxl.format.Alignment.CENTRE);//单元格中的内容水平方向居中
        titleFormate.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//单元格的内容垂直方向居中
        Label title = new Label(0,0,"JExcelApi支持数据类型636f70797a64331详细说明",titleFormate);
        sheet.setRowView(0, 600, false);//设置第一行的高度
        sheet.addCell(title);
        
        //创建要显示的具体内容
        WritableFont color = new WritableFont(WritableFont.ARIAL);//选择字体
        color.setColour(Colour.GOLD);//设置字体颜色为金黄色
        WritableCellFormat colorFormat = new WritableCellFormat(color);
        Label formate = new Label(0,1,"数据格式",colorFormat);
        sheet.addCell(formate);
        Label floats = new Label(1,1,"浮点型");
        sheet.addCell(floats);
        Label integers = new Label(2,1,"整型");
        sheet.addCell(integers);
        Label booleans = new Label(3,1,"布尔型");
        sheet.addCell(booleans);
        Label dates = new Label(4,1,"日期格式");
        sheet.addCell(dates);
        
        Label example = new Label(0,2,"数据示例",colorFormat);
        sheet.addCell(example);
        //浮点数据
        //设置下划线
        WritableFont underline= new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.NO_BOLD,false,UnderlineStyle.SINGLE);
        WritableCellFormat greyBackground = new WritableCellFormat(underline);
        greyBackground.setBackground(Colour.GRAY_25);//设置背景颜色为灰色
        Number number = new Number(1,2,3.1415926535,greyBackground);
        sheet.addCell(number);
        //整形数据
        WritableFont boldNumber = new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//黑体
        WritableCellFormat boldNumberFormate = new WritableCellFormat(boldNumber);
        Number ints = new Number(2,2,15042699,boldNumberFormate);
        sheet.addCell(ints);
        //布尔型数据
        Boolean bools = new Boolean(3,2,true);
        sheet.addCell(bools);
        //日期型数据
        //设置黑体和下划线
        WritableFont boldDate = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD,false,UnderlineStyle.SINGLE);
        WritableCellFormat boldDateFormate = new WritableCellFormat(boldDate,DateFormats.FORMAT1);
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        DateTime dt = new DateTime(4,2,date,boldDateFormate);
        sheet.addCell(dt);
        //把创建的内容写入到输出流中,并关闭输出流
        workbook.write();
        workbook.close();
        os.close();
        
    }
}


第一步:如何用POI操作Excel

@Test
public void createXls() throws Exception{
//声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
//声明表
HSSFSheet sheet = wb.createSheet("第一个表");
//声明行
HSSFRow row = sheet.createRow(7);
//声明列
HSSFCell cel = row.createCell(3);
//写入数据
cel.setCellValue("你也好");

FileOutputStream fileOut = new FileOutputStream("d:/a/b.xls");
wb.write(fileOut);
fileOut.close();
}

第二步:导出指定数据库的所有表
分析:
1:某个数数据库有多少表,表名e799bee5baa6e58685e5aeb9365是什么?―――DataBaseMetadate.getMetadate().getTables(null,null,null,new String[]{Table}); - excel的文件名称。
2:对每一个表进行select * 操作。 - 每一个sheet的名称。
3:分析表结构,rs.getMetadate(); ResultSetMedated
4:多个列,列名是什么.  - 字段名就是sheet的第一行信息。
5:获取每一行的数据 – 放到sheet第一行以后。

@Test
public void export() throws Exception{
//声明需要导出的数据库
String dbName = "focus";
//声明book
HSSFWorkbook book = new HSSFWorkbook();
//获取Connection,获取db的元数据
Connection con = DataSourceUtils.getConn();
//声明statemen
Statement st = con.createStatement();
//st.execute("use "+dbName);
DatabaseMetaData dmd = con.getMetaData();
//获取数据库有多少表
ResultSet rs = dmd.getTables(dbName,dbName,null,new String[]{"TABLE"});
//获取所有表名 - 就是一个sheet
List<String> tables = new ArrayList<String>();
while(rs.next()){
String tableName = rs.getString("TABLE_NAME");
tables.add(tableName);
}
for(String tableName:tables){
HSSFSheet sheet = book.createSheet(tableName);
//声明sql
String sql = "select * from "+dbName+"."+tableName;
//查询数据
rs = st.executeQuery(sql);
//根据查询的结果,分析结果集的元数据
ResultSetMetaData rsmd = rs.getMetaData();
//获取这个查询有多少行
int cols = rsmd.getColumnCount();
//获取所有列名
//创建第一行
HSSFRow row = sheet.createRow(0);
for(int i=0;i<cols;i++){
String colName = rsmd.getColumnName(i+1);
//创建一个新的列
HSSFCell cell = row.createCell(i);
//写入列名
cell.setCellValue(colName);
}
//遍历数据
int index = 1;
while(rs.next()){
row = sheet.createRow(index++);
//声明列
for(int i=0;i<cols;i++){
String val = rs.getString(i+1);
//声明列
HSSFCell cel = row.createCell(i);
//放数据
cel.setCellValue(val);
}
}
}
con.close();
book.write(new FileOutputStream("d:/a/"+dbName+".xls"));
}

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网