首先,在excel模板中适当的位置处加上特殊标记,比如 $内容$。
接着,用BufferedReader把模板中的所有字符串取出来,放入StringBuffer对象中。
第三,将StringBuffer对象中所有$内容$ replace掉,换成数据库中取出的结果。
第四,done。
接着,用BufferedReader把模板中的所有字符串取出来,放入StringBuffer对象中。
第三,将StringBuffer对象中所有$内容$ replace掉,换成数据库中取出的结果。
第四,done。
package cn.com.enjoysoft.connection.db;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
@SuppressWarnings("serial")
public class DownExcel extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String fileName = sdf.format(new Date()) + "导出数据";
fileName = response.encodeURL(new String(fileName.getBytes("GBK"), "iso8859-1"));// 转码
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachement;filename="
+ fileName + ".xls");
String type = request.getParameter("type");
try {
OutputStream os = response.getOutputStream();
HSSFWorkbook wb = generateWorkbook(type);
if (wb != null) {
wb.write(os);
}
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
static void processCell(HSSFCell cell, int value, HSSFCellStyle style) {
cell.setCellValue(value);
cell.setCellStyle(style);
}
static void processCell(HSSFCell cell, String value, HSSFCellStyle style) {
HSSFRichTextString _value = new HSSFRichTextString(value);
cell.setCellValue(_value);
cell.setCellStyle(style);
}
private HSSFWorkbook generateWorkbook(String type) {
Connection conn = null;
try {
conn = TodayConnection.getConnection();
Statement stmt = conn.createStatement();
String sql = null;
if (type == null || type.equals("")) {
sql = "select * from telNumber order by id desc";
} else {
sql = "select * from telNumber where counseling ='" + type + "' order by id desc";
}
ResultSet rs = stmt.executeQuery(sql);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("导出数据");
HSSFRow row = sheet.createRow((short) 0);
row.setHeight((short) (15 * 32));
HSSFCell[] headArray = new HSSFCell[7];
String[] headTitles = new String[] { "No.", "姓名", "电话", "公司名称",
"咨询项目", "备注", "时间" };
HSSFCellStyle style = workbook.createCellStyle();
// 这里解决背景颜色
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 字体
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
font.setFontName("Courier New");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int i = 0; i < headArray.length; i++) {
headArray[i] = row.createCell(i);
headArray[i].setCellStyle(style);
HSSFRichTextString value = new HSSFRichTextString(headTitles[i]);
headArray[i].setCellValue(value);
}
HSSFCellStyle styleData = workbook.createCellStyle();
styleData.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleData.setBottomBorderColor(HSSFColor.BLACK.index);
styleData.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleData.setLeftBorderColor(HSSFColor.BLACK.index);
styleData.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleData.setRightBorderColor(HSSFColor.BLACK.index);
styleData.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleData.setTopBorderColor(HSSFColor.BLACK.index);
styleData.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 字体
HSSFFont font1 = workbook.createFont();
font1.setFontHeightInPoints((short) 12);
font1.setFontName("Courier New");
styleData.setFont(font1);
// 循环查询的所有记录把每一行写入worksheet里面
int no = 1;
short rowNo = 1;
while (rs.next()) {
HSSFRow dataRow = sheet.createRow(rowNo++);
dataRow.setHeight((short) (12 * 32));
processCell(dataRow.createCell(0), no++, styleData);
processCell(dataRow.createCell(1), rs.getString("name"),
styleData);
processCell(dataRow.createCell(2), rs.getString("telNumber"),
styleData);
processCell(dataRow.createCell(3), rs.getString("corp"),
styleData);
processCell(dataRow.createCell(4), rs.getString("counseling"),
styleData);
processCell(dataRow.createCell(5), rs.getString("remark"),
styleData);
processCell(dataRow.createCell(6), rs.getString("jointime"),
styleData);
}
// 调整宽度
short[] widths = new short[] { 5, 15, 18, 22, 13, 50, 30 };
for (short k = 0; k < 7; k++) {
sheet.setColumnWidth(k, widths[k] * 256);
}
return workbook;
} catch (Exception e) {
} finally {
try {
// 关闭数据库连接
if (conn != null && !conn.isClosed())
conn.close();
} catch (SQLException e) {
}
}// END OF PROGRAMM
return null;
}
}
这里是详细的代码!需要poi-3.2-FINAL-20081019.jar自己下就可以了!
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
@SuppressWarnings("serial")
public class DownExcel extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String fileName = sdf.format(new Date()) + "导出数据";
fileName = response.encodeURL(new String(fileName.getBytes("GBK"), "iso8859-1"));// 转码
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachement;filename="
+ fileName + ".xls");
String type = request.getParameter("type");
try {
OutputStream os = response.getOutputStream();
HSSFWorkbook wb = generateWorkbook(type);
if (wb != null) {
wb.write(os);
}
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
static void processCell(HSSFCell cell, int value, HSSFCellStyle style) {
cell.setCellValue(value);
cell.setCellStyle(style);
}
static void processCell(HSSFCell cell, String value, HSSFCellStyle style) {
HSSFRichTextString _value = new HSSFRichTextString(value);
cell.setCellValue(_value);
cell.setCellStyle(style);
}
private HSSFWorkbook generateWorkbook(String type) {
Connection conn = null;
try {
conn = TodayConnection.getConnection();
Statement stmt = conn.createStatement();
String sql = null;
if (type == null || type.equals("")) {
sql = "select * from telNumber order by id desc";
} else {
sql = "select * from telNumber where counseling ='" + type + "' order by id desc";
}
ResultSet rs = stmt.executeQuery(sql);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("导出数据");
HSSFRow row = sheet.createRow((short) 0);
row.setHeight((short) (15 * 32));
HSSFCell[] headArray = new HSSFCell[7];
String[] headTitles = new String[] { "No.", "姓名", "电话", "公司名称",
"咨询项目", "备注", "时间" };
HSSFCellStyle style = workbook.createCellStyle();
// 这里解决背景颜色
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 字体
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
font.setFontName("Courier New");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int i = 0; i < headArray.length; i++) {
headArray[i] = row.createCell(i);
headArray[i].setCellStyle(style);
HSSFRichTextString value = new HSSFRichTextString(headTitles[i]);
headArray[i].setCellValue(value);
}
HSSFCellStyle styleData = workbook.createCellStyle();
styleData.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleData.setBottomBorderColor(HSSFColor.BLACK.index);
styleData.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleData.setLeftBorderColor(HSSFColor.BLACK.index);
styleData.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleData.setRightBorderColor(HSSFColor.BLACK.index);
styleData.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleData.setTopBorderColor(HSSFColor.BLACK.index);
styleData.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 字体
HSSFFont font1 = workbook.createFont();
font1.setFontHeightInPoints((short) 12);
font1.setFontName("Courier New");
styleData.setFont(font1);
// 循环查询的所有记录把每一行写入worksheet里面
int no = 1;
short rowNo = 1;
while (rs.next()) {
HSSFRow dataRow = sheet.createRow(rowNo++);
dataRow.setHeight((short) (12 * 32));
processCell(dataRow.createCell(0), no++, styleData);
processCell(dataRow.createCell(1), rs.getString("name"),
styleData);
processCell(dataRow.createCell(2), rs.getString("telNumber"),
styleData);
processCell(dataRow.createCell(3), rs.getString("corp"),
styleData);
processCell(dataRow.createCell(4), rs.getString("counseling"),
styleData);
processCell(dataRow.createCell(5), rs.getString("remark"),
styleData);
processCell(dataRow.createCell(6), rs.getString("jointime"),
styleData);
}
// 调整宽度
short[] widths = new short[] { 5, 15, 18, 22, 13, 50, 30 };
for (short k = 0; k < 7; k++) {
sheet.setColumnWidth(k, widths[k] * 256);
}
return workbook;
} catch (Exception e) {
} finally {
try {
// 关闭数据库连接
if (conn != null && !conn.isClosed())
conn.close();
} catch (SQLException e) {
}
}// END OF PROGRAMM
return null;
}
}
这里是详细的代码!需要poi-3.2-FINAL-20081019.jar自己下就可以了!
如果是jsp页面的话,那么生成word很简单的,我以前做的那个系统最后就有个报表要提供下载和打印,都要求是word文档,我的解决方法:
1、做好一个table布局的jsp页面,在里面添好表名、表头,样式等
2、在servlet或者action中调用biz读取数据,然后写入session或者request中
3、转向到jsp页面,在页面中读取session或者request中的数据
4、要注意的是,这个jsp页面不是一般的页面,这个jsp页面的content-type要设置,改成这样:
<meta http-equiv="Content-Type" content="application/msword; charset=gb2312" />
这样就可以提供word格式的文档,而且会在客户端提供下载。
你要客户直接把做好的word下载下来就ok,稍微编辑一些字体大小或者样式(或者这些东西在jsp页面中全部做好),直接打印或者备案就ok