首先需要导入相关jar包
代码示例:
.jsp文件
<body>
<table id="test" style="width:400px;font-size: 12px;text-align:center;" border="1" cellspacing="0" bordercolor="black">
<tr>
<th>一一</th><th>一二</th><th>一三</th><th>一四</th><th>五</th><th>六</th>
</tr>
<tr>
<td>二一</td><td>二二</td><td>二三</td><td>二四</td><td>五</td><td>六</td>
</tr>
<tr>
<td>三一</td><td>三二</td><td>三三</td><td>三四</td><td>五</td><td>六</td>
</tr>
<tr>
<td>四一</td><td>四儿</td><td>四三</td><td>四四</td><td>五</td><td>六</td>
</tr>
<tr>
<td>五一</td><td>五二</td><td>五三</td><td>五四</td><td>五</td><td>六</td>
</tr>
</table>
</body>
2.js文件
<script type="text/javascript">
function btnExcel(){
var table=document.getElementById("test");
var tableData="";
var rows=table.rows.length;
for(var i=0;i<rows;i++){
for(var j=0;j<table.rows[i].cells.length;j++){
tableData+=table.rows[i].cells[j].innerHTML+';';
}
}
alert(tableData);
$.ajax({
type:'POST',
url:'firstservlet?time=new Date()',
data:{"condition":tableData,
"rows":rows
},
dataType:'text',
success:function(){
alert("导出成功");
},
error: function(){
alert("导出失败");
}
});
}
</script>
3.后台相关代码
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String[] tabString;
String testData=req.getParameter("condition");
int rows=Integer.parseInt(req.getParameter("rows"));
tabString=testData.split(";");
for(int i=0;i<tabString.length;i++){
System.out.println("当前的值是"+tabString[i]);
}
XSSFWorkbook xwb =null;
// System.out.println("\\DaoChuExcel\\WebContent\\template\\testExcel.xlsx");
FileInputStream fis = new FileInputStream("F:/testDemo.xlsx");
// xwb= new XSSFWorkbook();
xwb = new XSSFWorkbook(fis);
XSSFFont font=xwb.createFont();
font.setFontName("宋体");
font.setFontHeight(10);
font.setColor(new HSSFColor.BLUE().getIndex());
FileOutputStream fileout = null;
XSSFCellStyle CellStyle = xwb.createCellStyle();
CellStyle.setFillForegroundColor((short) 13);// 设置背景色
CellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
CellStyle.setFont(font);
XSSFSheet sheet =xwb.getSheetAt(0);
//XSSFSheet sheet=xwb.createSheet("Sheetxx");
int column=tabString.length/rows;
int m=0;
for(int i=2;i<rows+2;i++){
XSSFRow rowi=sheet.createRow(i);
for(int j=0;j<column;j++){
XSSFCell cell=rowi.createCell(j);
cell.setCellValue(tabString[m]);
//cell.setCellStyle(CellStyle);
m++;
}
}
try {
fileout = new FileOutputStream("F:\\textdemo1.xlsx");
xwb.write(fileout);
} catch (IOException e) {
System.out.println(e.toString());
} finally {
try {
fileout.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
最后效果图