乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > <em>java</em>中怎么把报表导出到excel-java 实现导出excel表,java

<em>java</em>中怎么把报表导出到excel-java 实现导出excel表,java

作者:乔山办公网日期:

返回目录:excel表格制作


1./**

* 出险信息导出到excel(fc)

* @param mapping

* @param form

* @param request

* @param response

* @throws IOException

*/

public void exportActoExcel(ActionMapping mapping, ActionForm form ,

HttpServletRequest request,HttpServletResponse response) throws IOException {

ActionErrors errors = new ActionErrors();

AcExcelBusi acBusi = new AcExcelBusi();

AccidentRecordForm arForm= (AccidentRecordForm) form;

AccidentRecordBusi arBusi = new AccidentRecordBusi();

// ////查询条件

FwUsers sessUser = (FwUsers)request.getSession().getAttribute(ConstValues.SESS_USER_MANAGE);

Map<String,Object> cisMap = arBusi.getTodoPageList(arForm,sessUser,errors);

List AcList = null;// 当页的记录

if (null != cisMap) {

AcList = (List) cisMap.get("list");

}


//导出excel的路径、文件名

String uuid = UUID.create("exp");

String path = request.getSession().getServletContext().getRealPath("/") + ConstValues.EXP_PATH_EXCEL + uuid + ".xls";

acBusi.exprotAcExcel(AcList, path,request);


response.sendRedirect("stdownload.jsp?path=" + path );


}

2./**

* 导出出险信息 fc

* @param jzForm

*            查询条件

* @param sessionUser

*            当前登录session用户

* @param errors

*            Action错误

* @return

*/

public void exprotAcExcel(List list, String path,HttpServletRequest request) {


try {

WritableWorkbook workbook = Workbook.createWorkbook(new File(path));// 创建工作簿(filePos为excel文件的路径)

WritableSheet sheet = workbook.createSheet("出险信息", 0);// 创建工作页


// 内容(居中)单元格样式

WritableCellFormat contentStyle = new WritableCellFormat(); //

contentStyle.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式

contentStyle.setBorder(jxl.format.Border.ALL,

jxl.format.BorderLineStyle.THIN); // 设置边e68a847a64339


// 一级标题单元格样式

WritableFont wf1 = new WritableFont(WritableFont.ARIAL, 15,

WritableFont.BOLD, false); // 定义格式 字体 下划线 斜体 粗体 颜色

WritableCellFormat titleStyle1 = new WritableCellFormat(wf1); //

titleStyle1.setBackground(jxl.format.Colour.GREEN); // 设置单元格的背景颜色

titleStyle1.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式

titleStyle1.setBorder(jxl.format.Border.ALL,

jxl.format.BorderLineStyle.THIN); // 设置边框

// 二级标题单元格样式

WritableFont wf2 = new WritableFont(WritableFont.ARIAL, 11,

WritableFont.BOLD, false); // 定义格式 字体 下划线 斜体 粗体 颜色

WritableCellFormat titleStyle2 = new WritableCellFormat(wf2); //

titleStyle2.setBackground(jxl.format.Colour.GREY_25_PERCENT); // 设置单元格的背景颜色

titleStyle2.setAlignment(jxl.format.Alignment.CENTRE); // 设置水平对齐方式

titleStyle2

.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 设置垂直对齐方式

titleStyle2.setBorder(jxl.format.Border.ALL,

jxl.format.BorderLineStyle.THIN); // 设置边框


WritableCellFormat titleStyle3 = new WritableCellFormat(wf1); //

titleStyle3.setBackground(jxl.format.Colour.BRIGHT_GREEN); // 设置单元格的背景颜色

titleStyle3.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式

titleStyle3.setBorder(jxl.format.Border.ALL,

jxl.format.BorderLineStyle.THIN); // 设置边框


// 设置冻结单元格

sheet.getSettings().setVerticalFreeze(2);

sheet.getSettings().setHorizontalFreeze(5);


sheet.setColumnView(0, 8); // 设置列的宽度

sheet.setColumnView(1, 10); // 设置列的宽度


sheet.setRowView(0, 0);


sheet.addCell(new Label(0, 0, "hysj5800294*#", titleStyle1));// 标题

sheet.addCell(new Label(0, 1, "出险信息 ", titleStyle2));// 标题

sheet.mergeCells(0, 2, 33, 2); // 合并单元格

sheet.addCell(new Label(0, 2, "出险信息 ", titleStyle1));// 标题


sheet.addCell(new Label(0, 3, "序号", titleStyle2));// 往单元格中填写数据

sheet.addCell(new Label(1, 3, "省内/省外", titleStyle2));// 往单元格中填写数据


if (list != null && list.size() > 0) {

for (int i = 0; i < list.size(); i++) {

sheet.setRowView(i + 3, 300); // 设置行高

//转换数据信息

//Object[] obj = (Object[]) list.get(i);

AccidentRecord ar = (AccidentRecord) list.get(i);


sheet.addCell(new Label(0, i + 4, String.valueOf(i + 1),contentStyle));// 往单元格中填写数据 序号

sheet.addCell(new Label(1, i + 4, ar.getLicenceProvince().toString(),contentStyle));//  省内/省外

}

 

}

workbook.write();// 书写到工作簿

workbook.close();// 关闭工作簿,输出完成

} catch (Exception e) {

e.printStackTrace();

}

}

}

3.功能可以实现,可以到处,点击下载确定。


4.打开已经下载的excel,如图显示结果。得到想要的结构。



导入数据库

	@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++) {//取得每个抬e799bee5baa6e997aee7ad94e58685e5aeb9331头名称对应的列           
          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支持数据类型详细说明",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();
        
    }
}

java导入导zhidao出excel实现方法详见:https://wenku.baidu.com/view/9e4a2be0f61fb7360b4c65a7.html

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateSimpleExcelToDisk
{
/**
* @功能:手工构建一个7a64e58685e5aeb9364简单格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "张三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);

return list;
}

public static void main(String[] args) throws Exception
{
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("学生表一");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("学号");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("年龄");
cell.setCellStyle(style);
cell = row.createCell((short) 3);
cell.setCellValue("生日");
cell.setCellStyle(style);

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,
List list = CreateSimpleExcelToDisk.getStudent();

for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,创建单元格,并设置值
row.createCell((short) 0).setCellValue((double) stu.getId());
row.createCell((short) 1).setCellValue(stu.getName());
row.createCell((short) 2).setCellValue((double) stu.getAge());
cell = row.createCell((short) 3);
cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
.getBirth()));
}
// 第六步,将文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/students.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

相关阅读

关键词不能为空

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