/*
* 保存excel中的图片(以文件形式保存,或者存入数据库)
*
* basePath:应用所在路径,附件存放路径:
* 参数:is是上传的附件文件流
*/
public void saveSheetImgByFile(String basePath,InputStream is) throws ParseException {
FileOutputStream os = null;
try {
Workbook wbk = Workbook.getWorkbook(is);
//建文件目录
File mkFile = new File(basePath);
if (!mkFile.exists() && !mkFile.isDirectory()) {
mkFile.mkdirs();
}
// 循环所有sheet
for (int k = 0; k < wbk.getNumberOfSheets(); k++) {
Sheet sheet = wbk.getSheet(k);
// 共有多少行
int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数
// 循环sheet的所有图片
for (int i = 0; i < imgNumber; i++) {
Image image = sheet.getDrawing(i);
byte[] imageData = image.getImageData();
String fileName = image.getImageFile().getName().trim()
+ ".jpg";
File file = new File(basePath+"/" + fileName);
os = new FileOutputStream(file);// 建立一个上传文件的输出流
os.write(imageData, 0, imageData.length);// 将文件写入服务器
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 将excel图片文件保存到数据库
*/
public void saveSheetImgByDB(InputStream is) throws ParseException,
ClassNotFoundException, SQLException, IOException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf8", "root", "root");
String INSERT_PICTURE = "insert into t_mypicture(name, photo) values (?, ?)";
PreparedStatement ps = null;
FileOutputStream os = null;
try {
Workbook wbk = Workbook.getWorkbook(is);
// 循环所有sheet
for (int k = 0; k < wbk.getNumberOfSheets(); k++) {
Sheet sheet = wbk.getSheet(k);
// 共有多少行
int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数
// 循环sheet的所有图片
for (int i = 0; i < imgNumber; i++) {
Image image = sheet.getDrawing(i);
byte[] imageData = image.getImageData();
String fileName = image.getImageFile().getName().trim()
+ ".jpg";
conn.setAutoCommit(false);
ps = conn.prepareStatement(INSERT_PICTURE);
ps.setString(1, fileName);
ps.setBytes(2, imageData);
ps.executeUpdate();
conn.commit();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.action方法调用:
ImportExcelUtil ieu = new ImportExcelUtil();
ExcelForm excelForm = (ExcelForm) form;
FormFile file = excelForm.getExcelFile();
// 附件方式保存
String basePath = request.getSession().getServletContext().getRealPath(
"/")+"excelFile";
try {
ieu.saveSheetImgByFile(basePath,file.getInputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 数据库方式保存
try {
ieu.saveSheetImgByDB(file.getInputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/LIUJIMMY/archive/2010/01/25/5253978.aspx