Java codepackage com.test.excel;
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.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.RichTextString;
import com.test.db.DB;
import com.test.serch.Xin;
import com.test.serch.Xlist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServlet;
public class excel extends HttpServlet
{
public static String outputFile = "c:\\test.xls";
@SuppressWarnings({ "deprecation", "unchecked" })
public boolean excel() throws SQLException
{
/*
*
* 创建excel表格
*
*
*
*/
HSSFWorkbook wb = new HSSFWorkbook();//创建一个工作间
HSSFSheet sheet = wb.createSheet("sheet1");//创建一个sheet
HSSFRow row = sheet.createRow(0);//创建一行
HSSFCell cell = row.createCell((short) 0);//创建这行的第一个元素.从0开始
cell.setCellValue("序号");//写入内容
cell = row.createCell((short) 1);
cell.setCellValue("书名");
cell = row.createCell((short) 2);
cell.setCellValue("数量");
/*
*
* 将数据库的信息存到链表里面
*
*
*
*
*/
ArrayList X=new ArrayList();
ResultSet rs=null;
Xin nu=new Xin();
String sql="select * from book" ;
DB sqle=new DB();
rs= sqle.db(sql);
while(rs.next())
{
Xin x=new Xin();
x.setXid(rs.getString(1));
x.setXname(rs.getString(2));
x.setXnumber(rs.getInt(5)-rs.getInt(6));
X.add(x);
}
System.out.println("链表长度"+ X.size());
/*
*
*
* 循环遍历链表取出来值放到相应的excel表格的行列中;
*
* 取值方法: 先得到链表的第i个位置一组,然后在把这组相应的内容get出来
*
*
*
*
*/
for(int i = 0 ; i < X.size() ; i++)
{
Xin x = X.get(i);
row = sheet.createRow(i+1);
cell = row.createCell((short) 0);
cell.setCellValue(x.getXid());
cell = row.createCell((short) 1);
cell.setCellValue(x.getXname());
cell = row.createCell((short) 2);
cell.setCellValue(x.getXnumber());
}
/*
*
*
*
* 内容填好后,生成该文件,并给它相应的地址位置!
*
*
*
*
*/
File file = new File("c:\\abc.xls");
//创建一个File 拿来当缓存用.也就是先将内存中的excel写入File中.然后再将File转换成输出流
try {
//OutputStream out = new FileOutputStream("abc.xls");
FileOutputStream out = new FileOutputStream(outputFile);
wb.write(out);//写入File
out.flush();
// 操作结束,关闭文件
out.close();
System.out.println("文件生成...");
return true;
} catch (Exception e) {
System.out.println(e.toString());
return false;
}
}
}