java导入导出excel表格

这里是通过jxl实现对excel的导入导出的,可以动态创建本地excel,读取本地excel,写入excel。

只需导入jxl.jar包即可;

基本操作:

一:创建本地excel:

//创建EXECEL,添加数据,通过输出流输出到客户端下载
		public static void createExecel(HttpServletRequest request,HttpServletResponse response,String fileName){
			OutputStream os=null;
			try {
				os=response.getOutputStream();
				response.reset();
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment;filename="+fileName);
				response.setContentType("application/msexcel");
				//创建工作薄
				WritableWorkbook wwb=Workbook.createWorkbook(os);
				//创建新的一页
				WritableSheet sheet=wwb.createSheet("First sheet", 0);
				//创建要显示的内容,第一个参数为列,第二个参数为行,第三个参数为内容
				Label xuexiao=new Label(0,0,"学校");
				sheet.addCell(xuexiao);
				Label zhuanye=new Label(1,0,"专业");
				sheet.addCell(zhuanye);
				Label xuexiao1=new Label(0,1,"清华大学");
				sheet.addCell(xuexiao1);
				Label zhuanye1=new Label(1,1,"软件工程");
				sheet.addCell(zhuanye1);
				//把创建的内容写入输出流,并关闭
				wwb.write();
				wwb.close();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

二:创建带有 样式的EXECEL

//创建带有 样式的EXECEL,添加数据,通过输出流输出到客户端下载
			public static void createStyleExecel(HttpServletRequest request,HttpServletResponse response,String fileName){
				OutputStream os=null;
				try {
					os=response.getOutputStream();
					response.reset();
					response.setCharacterEncoding("utf-8");
					response.setHeader("Content-Disposition", "attachment;filename="+fileName);
					response.setContentType("application/msexcel");
					//创建工作薄
					WritableWorkbook wwb=Workbook.createWorkbook(os);
					//创建新的一页
					WritableSheet sheet=wwb.createSheet("First sheet", 0);
					//构造表头,合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
					sheet.mergeCells(0, 0, 1, 0);
					//设置字体为Arial,字号为10,黑体显示
					WritableFont wf=new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);
					//生成一个单元格样式控制对象
					WritableCellFormat wcf=new WritableCellFormat(wf);
					//单元格的内容水平方向上居中
					wcf.setAlignment(jxl.format.Alignment.CENTRE);
					//单元格的内容垂直方向上居中
					wcf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
					//创建要显示的内容,第一个参数为列,第二个参数为行,第三个参数为内容
					Label title=new Label(0,0,"学校专业信息表",wcf);
					//设置第一行的高度
					sheet.setRowView(0,600,false);
					sheet.addCell(title);

					WritableFont wf1=new WritableFont(WritableFont.ARIAL);
					wf1.setColour(Colour.GOLD);//设置字体颜色
					WritableCellFormat wcf1=new WritableCellFormat(wf1);

					Label fd=new Label(0,1,"学校",wcf1);
					sheet.addCell(fd);
					Label be=new Label(1,1,"专业",wcf1);
					sheet.addCell(be);
					Label rq=new Label(0,2,"清华大学");
					sheet.addCell(rq);
					Label rq1=new Label(1,2,"软件工程");
					sheet.addCell(rq1);				

					//把创建的内容写入输出流,并关闭
					wwb.write();
					wwb.close();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

三:创建excel,从数据库读取数据写入excel

//创建EXECEL,从数据库导入数据,输出到客户端下载
		public static void createExecelData(HttpServletRequest request,HttpServletResponse response,StudentService studentService,String fileName){
			OutputStream os=null;
			try {
				os=response.getOutputStream();
				response.reset();
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment;filename="+fileName);
				response.setContentType("application/msexcel");
				//创建工作薄
				WritableWorkbook wwb=Workbook.createWorkbook(os);
				//创建新的一页
				WritableSheet sheet=wwb.createSheet("First sheet", 0);
				//创建要显示的内容,第一个参数为列,第二个参数为行,第三个参数为内容
				Label studentId=new Label(0,0,"ID");
				sheet.addCell(studentId);
				Label studentName=new Label(1,0,"姓名");
				sheet.addCell(studentName);
				List<Student> students=studentService.findByHq("from Student s", null);
				for(int i=0;i<students.size();i++){
					studentId=new Label(0,i+1,students.get(i).getStudentId()+"");
					studentName=new Label(1,i+1,students.get(i).getStudentName());
					sheet.addCell(studentId);
					sheet.addCell(studentName);
				}

				//把创建的内容写入输出流,并关闭
				wwb.write();
				wwb.close();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	

四:读取本地EXECEL文件数据

//读取本地EXECEL文件数据
	public static void readExcel(StudentService studentService,String filePath){
		//创建只读Workbook对象
		Workbook wb=null;
		try {
			InputStream is=new FileInputStream(filePath);
			wb=Workbook.getWorkbook(is);
			//创建sheet表,sheet下标从0开始
			Sheet  sheet=wb.getSheet(0);
			//获取sheet表的总列数
			int cols=sheet.getColumns();
			System.out.println("列数:"+cols);
			//获取sheet表的总行数
			int rows=sheet.getRows();
			System.out.println("行数:"+rows);
			//遍历每个单元格
			List<Student> students=new ArrayList<Student>();
			for(int i=1;i<rows;i++){
				Student s=new Student();
				for(int j=0;j<cols;j++){
					Cell cell=sheet.getCell(j,i);
					System.out.println((i+","+j+":")+cell.getContents());
					if(j==0){
						s.setStudentId(Integer.valueOf(cell.getContents()));
					}else{
						s.setStudentName(cell.getContents());
					}
				}
				students.add(s);
			}
			studentService.saveBatch(students);
			System.out.println("batch ok");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

五 :实现通过jsp导入数据,到数据库:

分两步实现,先把文件上传到服务器本地,再读取本地excel文件

<form action="impExcel" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit" value="导入">
</form>
public String executeImport(){
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		//首先将文件上传至服务器 f:\\temp目录
		InputStream is=null;
		OutputStream os=null;
		try {
			System.out.println("in upload");
			 is=new FileInputStream(file);
			  path="F:\\temp\\"+fileFileName;
			 os=new FileOutputStream(new File(path));
			byte[] b=new byte[1024];
			int num;
			while((num=is.read(b))!=-1){
				os.write(b, 0, num);
				os.flush();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
			e.printStackTrace();
			}
		}
		//从服务器读取Execel
		ExcelUtil.readExcel(studentService,"F:\\temp\\"+fileFileName);
		System.out.println("导入 execel ok");

		return "all";
	}

六 导出excel

<a href="expExcel">导出</a>
public String executeExport(){
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
//		ExcelUtil.createExecel(request, response,fileName);
		ExcelUtil.createExecelData(request, response,studentService,fileName);
//		ExcelUtil.createStyleExecel(request, response,fileName);
		System.out.println("导出 execel ok");
		return null;
	}



时间: 2024-08-01 08:57:55

java导入导出excel表格的相关文章

c# Datagridview控件导入/导出excel表格

在写商业软件的时候,我们会经常遇到对excel表格的操控,最常见的就是Datagridview控件导入/导出excel表格.我也同样遇到了.运用了自己的知识,再加上网上的[大部分]都过期的源码,自己写出了这两个方法,当然,和绑定数据库一样,都用到了databel类. 导入: //private string fileName; /// <summary> /// 将DataGridView中数据导入到Excel /// </summary> /// <param name=&

PHP导入导出excel表格图片(转)

写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用谈了.呵呵.(COM方式不讲了,这种可读的太多了,我也写过利用wps等进行word等的生成之类的文章 )但是在读的时候,只用过一种,具体是什么忘了,要回去翻代码了.基本上导出的文件分为两种:1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已.修改这种文件后再保存,通常会提示你是否要转换成Excel文件.优

从SQL Server 2005 中 导入 导出 excel 表格

1.从 数据库 中 导出 excel  表格 定义 一个 gridview1 protected void Button1_Click(object sender, EventArgs e) //倒出数据 {     if (GridView1.Rows.Count == 0)   {       return;    }   else  {       GridView1.AllowPaging = false;//先将数据分页取消,才能全部导出数据      bind(); Export("

java导入导出Excel数据的要点记录

< 客户端的B/S架构输出方式 加下划线这部分代码是B/S模式中采用的输出方式, //获得输出流,该输出流的输出介质是客户端浏览器 OutputStream output=response.getOutputStream(); response.reset(); response.setHeader("Content-disposition","attachment; filename=temp.xls"); response.setContentType(&

java导入导出excel常用操作小结及简单示例

POI中常用设置EXCEL的操作小结: 操作excel如下 HSSFWorkbook wb = new HSSFWorkbook();  //创建一个webbook,对应一个Excel文件 HSSFSheet sheet = wb.createSheet();    //添加一个sheet,对应Excel文件中的sheet 构造方法可以有参也可以无参wb.createSheet("学生表一") HSSFRow row = sheet.createRow((int) 0);  //she

Java导入导出Excel和Word

目的 实现Excel/Word导入导出,分以下步骤 导入 上传文件 解析Excel/Word里面的内容 导出 生成Excel/Word文件 文件下载 如何实现 上传文件----------Commons FileUpload上传组件 Excel/Word-------Apache POI----Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 下载文件----------ServletOutputStream直接输出文

java 导入导出excel

一,导出excel 1,使用excel模板 public void exportLog() throws Exception{ SystemUser currentUsr = getCurrentSystemUser(); //该用户的所有日志 List<TLogInfo> loglist=logService.getLogInfosByUserId(currentUsr.getId()); List<TLogInfo> list=new ArrayList<TLogInfo

java导入导出excel

maven <!--POI--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <a

解决导入导出Excel表格文字乱码问题

前端可以在请求头里面加上一句代码就搞定 responseType: 'arraybuffer' 原文地址:https://www.cnblogs.com/minjh/p/12299920.html