|
|
|
|
|
分享者:Vashon
分享来源:CSDN博客
下面这些是在开发中用到的一些东西,有的代码贴的不是完整的,只是贴出了关于操作EXCEL的代码:
jxl是一个*国人写的java操作excel的工具, 在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI。其中功能相对POI比较弱一点。但jExcelAPI对中文 支持非常好,API是纯Java的, 并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。 另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。
使用如下:
搭建环境
将下载后的文件解包,得到jxl.jar,放入classpath,安装就完成了。
基本操作
一、创建文件
拟生成一个名为“test.xls”的Excel文件,其中第一个工作表被命名为
“第一页”,大致效果如下:
代码
-
package test;
-
-
-
import java.io.File;
-
-
import jxl.Workbook;
-
import jxl.write.Label;
-
import jxl.write.WritableSheet;
-
import jxl.write.WritableWorkbook;
-
-
public class CreateExcel {
-
public static void main(String args[]) {
-
try {
-
-
WritableWorkbook book = Workbook.createWorkbook( new File( " test.xls " ));
-
-
WritableSheet sheet = book.createSheet( " 第一页 " , 0 );
-
-
-
Label label = new Label( 0 , 0 , " test " );
-
-
-
sheet.addCell(label);
-
-
-
-
-
jxl.write.Number number = new jxl.write.Number( 1 , 0 , 555.12541 );
-
sheet.addCell(number);
-
-
-
book.write();
-
book.close();
-
-
} catch (Exception e) {
-
System.out.println(e);
-
}
-
}
-
编译执行后,会产生一个Excel文件。
三、读取文件
以刚才我们创建的Excel文件为例,做一个简单的读取操作,程序代码如下:
代码
-
package test;
-
-
-
import java.io.File;
-
-
import jxl.Cell;
-
import jxl.Sheet;
-
import jxl.Workbook;
-
-
public class ReadExcel {
-
public static void main(String args[]) {
-
try {
-
Workbook book = Workbook.getWorkbook( new File( " test.xls " ));
-
-
Sheet sheet = book.getSheet( 0 );
-
-
Cell cell1 = sheet.getCell( 0 , 0 );
-
String result = cell1.getContents();
-
System.out.println(result);
-
book.close();
-
} catch (Exception e) {
-
System.out.println(e);
-
}
-
}
-
程序执行结果:test
四、修改文件
利用jExcelAPI可以修改已有的Excel文件,修改Excel文件的时候,除了打开文件的方式不同之外,
其他操作和创建Excel是一样的。下面的例子是在我们已经生成的Excel文件中添加一个工作表:
代码
-
package test;
-
-
import java.io.File;
-
-
import jxl.Workbook;
-
import jxl.write.Label;
-
import jxl.write.WritableSheet;
-
import jxl.write.WritableWorkbook;
-
-
public class UpdateExcel {
-
public static void main(String args[]) {
-
try {
-
-
Workbook wb = Workbook.getWorkbook( new File( " test.xls " ));
-
-
WritableWorkbook book = Workbook.createWorkbook( new File( " test.xls " ),
-
wb);
-
-
WritableSheet sheet = book.createSheet( " 第二页 " , 1 );
-
sheet.addCell( new Label( 0 , 0 , " 第二页的测试数据 " ));
-
book.write();
-
book.close();
-
} catch (Exception e) {
-
System.out.println(e);
-
}
-
}
-
其他操作
一、 数据格式化
在Excel中不涉及复杂的数据类型,能够比较好的处理字串、数字和日期已经能够满足一般的应用。
1、 字串格式化
字符串的格式化涉及到的是字体、粗细、字号等元素,这些功能主要由WritableFont和
WritableCellFormat类来负责。假设我们在生成一个含有字串的单元格时,使用如下语句,
为方便叙述,我们为每一行命令加了编号:
代码
-
WritableFont font1 =
-
new WritableFont(WritableFont.TIMES, 16 ,WritableFont.BOLD); ①
-
-
WritableCellFormat format1 = new WritableCellFormat(font1); ②
-
-
Label label = new Label( 0 , 0 ,”data 4 test”,format1) ③
-
-
-
其中①指定了字串格式:字体为TIMES,字号16,加粗显示。WritableFont有非常丰富的
-
构造子,供不同情况下使用,jExcelAPI的java-doc中有详细列表,这里不再列出。
-
-
②处代码使用了WritableCellFormat类,这个类非常重要,通过它可以指定单元格的各种
-
属性,后面的单元格格式化中会有更多描述。
-
-
③处使用了Label类的构造子,指定了字串被赋予那种格式。
-
-
在WritableCellFormat类中,还有一个很重要的方法是指定数据的对齐方式,比如针对我们
-
上面的实例,可以指定:
-
-
-
format1.setAlignment(jxl.format.Alignment.CENTRE);
-
-
-
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
二、单元格操作
Excel中很重要的一部分是对单元格的操作,比如行高、列宽、单元格合并等,所幸jExcelAPI
提供了这些支持。这些操作相对比较简单,下面只介绍一下相关的API。
1、 合并单元格
代码
-
WritableSheet.mergeCells( int m, int n, int p, int q);
-
-
-
WritableSheet sheet = book.createSheet(“第一页”, 0 );
-
-
-
sheet.mergeCells( 0 , 0 , 5 , 0 );
合并既可以是横向的,也可以是纵向的。合并后的单元格不能再次进行合并,否则会触发异常。
2、 行高和列宽
代码
-
WritableSheet.setRowView( int i, int height);
-
-
-
-
-
sheet.setRowView( 0 , 200 );
-
-
WritableSheet.setColumnView( int i, int width);
-
-
-
-
-
sheet.setColumnView( 0 , 30 );
-
-
jExcelAPI还有其他的一些功能,比如插入图片等,这里就不再一一介绍,读者可以自己探索。
其中:如果读一个excel,需要知道它有多少行和多少列,如下操作:
代码
-
Workbook book = Workbook.getWorkbook( new File( " 测试1.xls " ));
-
-
Sheet sheet = book.getSheet( 0 );
-
-
int columnum = sheet.getColumns();
-
int rownum = sheet.getRows();
-
System.out.println(columnum);
-
System.out.println(rownum);
-
for ( int i = 0 ; i < rownum; i ++ )
-
{
-
for ( int j = 0 ; j < columnum; j ++ ) {
-
Cell cell1 = sheet.getCell(j, i);
-
String result = cell1.getContents();
-
System.out.print(result);
-
System.out.print( " /t " );
-
}
-
System.out.println();
-
}
-
book.close();
|
ExcelBean.java文件用于生成Excel
代码
-
public class ExcelBean {
-
-
public String expordExcel(OutputStream os, List courseList,List studentList)
-
throws Exception {
-
-
WritableWorkbook wbook = Workbook.createWorkbook(os);
-
String tmptitle = "课程“"+((Course_info)courseList.get(0)).getCource_name()+"”的选课学生列表";
-
WritableSheet wsheet = wbook.createSheet("第一页", 0);
-
-
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,
-
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
-
Colour.BLACK);
-
WritableCellFormat wcfFC = new WritableCellFormat(wfont);
-
wsheet.addCell(new Label(1, 0, tmptitle, wcfFC));
-
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,
-
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
-
Colour.BLACK);
-
wcfFC = new WritableCellFormat(wfont);
-
-
wsheet.addCell(new Label(0, 2, "课程名称"));
-
wsheet.addCell(new Label(1, 2, "学 号"));
-
.........
-
for(int i=3;i<studentList.size()+3;i++)
-
{
-
wsheet.addCell(new Label(0, i, ((Course_info)courseList.get(0)).getCource_name()));
-
wsheet.addCell(new Label(1, i, ((Student_info)studentList.get(0)).getStudentID()));
-
...........
-
}
-
-
wbook.write();
-
wbook.close();
-
os.close();
-
return "success";
-
}
-
}
控制器:
代码
-
public class EExcelDownController extends AbstractController {
-
-
private ICourse_infoManage courseManage;
-
-
public void setCourseManage(ICourse_infoManage courseManage) {
-
this.courseManage = courseManage;
-
}
-
-
@Override
-
protected ModelAndView handleRequestInternal(HttpServletRequest request,
-
HttpServletResponse response) throws Exception {
-
Integer course_id=new Integer(request.getParameter("course_id"));
-
List courseList=this.courseManage.getCourseById(course_id);
-
List studentList = this.courseManage.getStudentByCourseId(course_id);
-
try {
-
OutputStream os = response.getOutputStream();
-
response.reset();
-
response.setHeader("Content-disposition", "attachment; filename=student.xls");
-
response.setContentType("application/msexcel");
-
ExcelBean excelBean = new ExcelBean();
-
excelBean.expordExcel(os,courseList,studentList);
-
} catch (Exception e) {
-
System.out.println(e);
-
}
-
return null;
-
}
-
}
|
将Excel文件内容写入到数据库
代码
-
public class EStudentInsertExcelController extends SimpleFormController {
-
-
private IStudent_infoManage studentManage;
-
-
@Override
-
protected ModelAndView onSubmit(HttpServletRequest request,
-
HttpServletResponse response, Object command, BindException errors)
-
throws Exception {
-
Student_info student_info = (Student_info) command;
-
try {
-
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
-
MultipartFile file = multipartRequest.getFile( " Excelfile " );
-
File toFile = new File( " c://学生信息临时文件.xls " );
-
file.transferTo(toFile);
-
Workbook book = Workbook.getWorkbook(toFile);
-
Sheet sheet = book.getSheet( 0 );
-
int row = sheet.getRows();
-
int column = sheet.getColumns();
-
System.out.println( " 数据行数= " + row);
-
System.out.println( " 数据列数= " + column);
-
for ( int i = 1 ;i < row;i ++ )
-
{
-
for ( int j = 0 ;j < column;j ++ )
-
{
-
System.out.println( " j= " + j);
-
sheet.getCell(j, i).getContents();
-
student_info.setStudentID(sheet.getCell(j, i).getContents());
-
........................
-
}
-
if ( this .studentManage.getStudentByStudentID(
-
student_info.getStudentID()).size() != 0 )
-
return new ModelAndView( " education/e-studentInfoAddError " );
-
this .studentManage.insertStudent_info(student_info);
-
}
-
book.close();
-
return new ModelAndView( " education/e-studentInfoAddExcelSuccess " , " row " , new Integer(row - 1 ));
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
return new ModelAndView( " education/e-studentInfoAddExcelError " );
-
}
-
-
public void setStudentManage(IStudent_infoManage studentManage) {
-
this .studentManage = studentManage;
-
}
-
}
|
spring 生成Excel和PDF文件
HTML页面并不总是向用户显示数据输出的最好方式,有时候需要生成不可改变的文件打印,PDF可能是种不错的选择。
Spring支持从数据动态生成PDF或Excel文件
下面这个简单实现的例子实现了spring输出PDF和Excel文件,为了使用Excel电子表格,你需要在你的classpath中加入poi-2.5.1.jar库文件,而对PDF文件,则需要iText.jar文件。它们都包含在Spring的主发布包中。
下面是测试项目代码:
1、控制器配置代码
代码
-
<?xml version="1.0" encoding="UTF-8"?>
-
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
-
-
<beans>
-
<bean id="beanNameViewResolver"
-
class="org.springframework.web.servlet.view.BeanNameViewResolver" />
-
-
<bean id="viewController" class="com.zhupan.spring.ViewController" />
-
<bean id="urlMapping"
-
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
-
<property name="mappings">
-
<props>
-
<prop key="/view*.shtml">viewController</prop>
-
</props>
-
</property>
-
</bean>
-
</beans>
3、用于Excel视图的视图子类化
为了在生成输出文档的过程中实现定制的行为,我们将继承合适的抽象类。对于Excel,这包括提供一个 org.springframework.web.servlet.view.document.AbstractExcelView的子类,并实现 buildExcelDocument方法。
代码
-
public class ViewExcel extends AbstractExcelView {
-
-
public void buildExcelDocument(
-
Map model, HSSFWorkbook workbook,
-
HttpServletRequest request, HttpServletResponse response)
-
throws Exception {
-
-
HSSFSheet sheet = workbook.createSheet("list");
-
sheet.setDefaultColumnWidth((short) 12);
-
-
-
HSSFCell cell = getCell(sheet, 0, 0);
-
setText(cell, "Spring Excel test");
-
-
HSSFCellStyle dateStyle = workbook.createCellStyle();
-
dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
-
cell = getCell(sheet, 1, 0);
-
cell.setCellValue(new Date());
-
cell.setCellStyle(dateStyle);
-
getCell(sheet, 2, 0).setCellValue(458);
-
-
HSSFRow sheetRow = sheet.createRow(3);
-
for (short i = 0; i < 10; i++) {
-
sheetRow.createCell(i).setCellValue(i * 10);
-
}
-
-
}
-
-
}
4、用于PDF视图的视图子类化
需要象下面一样继承org.springframework.web.servlet.view.document.AbstractPdfView,并实现buildPdfDocument()方法。
代码
-
public class ViewPDF extends AbstractPdfView {
-
public void buildPdfDocument(Map model, Document document,
-
PdfWriter writer, HttpServletRequest request,
-
HttpServletResponse response) throws Exception {
-
-
List list = (List) model.get("list");
-
-
for (int i = 0; i < list.size(); i++)
-
document.add(new Paragraph((String) list.get(i)));
-
}
-
-
}
5、其他文件
1)控制器ViewController
代码
-
public class ViewController extends MultiActionController{
-
-
public ModelAndView viewPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
List list = new ArrayList();
-
Map model=new HashMap();
-
list.add("test1");
-
list.add("test2");
-
model.put("list",list);
-
ViewPDF viewPDF=new ViewPDF();
-
return new ModelAndView(viewPDF,model);
-
}
-
-
public ModelAndView viewExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
List list = new ArrayList();
-
Map model=new HashMap();
-
list.add("test1");
-
list.add("test2");
-
model.put("list",list);
-
ViewExcel viewExcel=new ViewExcel();
-
return new ModelAndView(viewExcel,model);
-
}
-
}
2)web.xml
代码
-
<?xml version="1.0" encoding="UTF-8"?>
-
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
-
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
-
-
<display-name>springPDFTest</display-name>
-
<servlet>
-
<servlet-name>springPDFTest</servlet-name>
-
<servlet-class>
-
org.springframework.web.servlet.DispatcherServlet
-
</servlet-class>
-
<load-on-startup>1</load-on-startup>
-
</servlet>
-
-
<servlet-mapping>
-
<servlet-name>springPDFTest</servlet-name>
-
<url-pattern>*.shtml</url-pattern>
-
</servlet-mapping>
-
-
<welcome-file-list>
-
<welcome-file>index.jsp</welcome-file>
-
</welcome-file-list>
-
-
</web-app>
3)index.jsp
代码
-
<%@ page contentType="text/html; charset=gb2312"%>
-
-
<a href="viewPDF.shtml">PDF视图打开 </a>
-
<br>
-
<a href="viewExcel.shtml">Excel视图打开</a>
|
网页链接到Excel打开时乱码解决办法:
问题:
代码
-
< a href ="excel/test.xls" > 打开 </ a > 【乱码】
解决方法:
web.xml里加上 :
代码
-
< mime-mapping >
-
< extension > xls </ extension >
-
< mime-type > application/vnd.ms-excel </ mime-type >
-
</ mime-mapping >
让他下载然后直接打开即可
Stay Hungry, Stay Foolish, Walking in Life
发表于
2015-04-19 13:26
楊博程
阅读( 297)
评论()
编辑
收藏
举报
|
|