本文介绍将一个Excel文件上传后,修改Excel表中数据,再从新写入到新的Excel表
1.使用myeclipse创建web工程,
2.添加struts2 使用struts2的分装工具将文件 上传
3.导入poi-3.0.2-FINAL-20080204.jar
4.Excel的操作
try {
//传入的文件
FileInputStream fileInput = new FileInputStream(file);
//poi包下的类读取excel文件
POIFSFileSystem ts = new POIFSFileSystem(fileInput);
// 创建一个webbook,对应一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook(ts);
//对应Excel文件中的sheet,0代表第一个
HSSFSheet sh = workbook.getSheetAt(0);
//修改excle表的第5行数据
for(int i=2;i<19;i++){
//对第五行的数据修改
sh.getRow(4).getCell((short)i).setCellValue(100210+i);
}
//将修改后的文件写出到D:\\excel目录下
FileOutputStream os = new FileOutputStream("D:\\excel\\辅机1.xls");
os.flush();
//将Excel写出
workbook.write(os);
//关闭流
fileInput.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
5 struts配置
<struts>
<package name="upload" extends="struts-default">
<action name="upFile" class="excelAction.Excel">
<!-- 上传成功后跳转到success.jsp页面 -->
<result name="success">/sucess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
6.ExcelAction
private File upload;
private String uploadContentType;
private String uploadFileName;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String execute() throws Exception {
FileUpload.upload(upload,uploadContentType,uploadFileName);
return SUCCESS;
}
7.jsp页面(form必须添加enctype="multipart/form-data"
<form action="${pageContext.request.contextPath }/upFile.action" enctype="multipart/form-data" method="post">
文件:<input type="file" name="upload"/><br/>
<input type="submit" value="Excel">"
</form>
本文介绍将一个Excel文件上传后,修改Excel表中数据,再从新写入到新的Excel表
需要java学习的资料,搜索微信公众号javamy012