怎样把读出的数据写在excel表格中,求代码

public class XMLParseDemo
{

public static void main(String[] args){
    try
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:\\file\\never_230.txt")), "UTF-8"));
        String lineTxt = null;
        while ((lineTxt = br.readLine()) != null) {
            parseXML(lineTxt);


        }
        br.close();
    }catch(Exception e){

    }


    }



public static Document parseXML(String xml) throws ParserConfigurationException, SAXException, IOException{
    StringReader sr = new StringReader(xml); 
    InputSource is = new InputSource(sr); 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder=factory.newDocumentBuilder(); 
    Document doc = builder.parse(is);

    NodeList _balanceSourceInfo = doc.getElementsByTagName("TcpCont");
    for (int j = 0; j < _balanceSourceInfo.getLength(); j++) { 
        Node node = _balanceSourceInfo.item(j); 
        NodeList employeeMeta = node.getChildNodes();
        for (int k = 0; k < employeeMeta.getLength(); k++) { 
            System.out.println(employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getFirstChild().getNodeValue());
        } 
    } 
    System.out.println("\n\n");
    NodeList balanceSourceInfo = doc.getElementsByTagName("ctroot");
    for (int j = 0; j < balanceSourceInfo.getLength(); j++) { 
        Node node = balanceSourceInfo.item(j); 
        NodeList employeeMeta = node.getChildNodes();
        for (int k = 0; k < employeeMeta.getLength(); k++) { 

            try {
                System.out.println(employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getFirstChild().getNodeValue());

            } catch (Exception e) {
                // TODO: handle exception
            }
        } 
    }
    System.out.println("\n\n");
    /*Node operationStatus = doc.getElementsByTagName("OperationStatus").item(0);
    System.out.println(operationStatus.getNodeName() + ":" + operationStatus.getFirstChild().getNodeValue());
    Node limitServID = doc.getElementsByTagName("LimitServID").item(0);
    System.out.println(limitServID.getNodeName() + ":" + limitServID.getFirstChild().getNodeValue());
    Node queryType = doc.getElementsByTagName("QueryType").item(0);
    System.out.println(queryType.getNodeName() + ":" + queryType.getFirstChild().getNodeValue());*/

    return doc;
}

}

我在eclipse打印台读出了数据,写io流的基础忘了

这个是工具类,什么都不用改,直接放到工具类目录下,一会给你来个例子
import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ExportExcelUtils {
/**
* 导出excel表格
*
* @param map
* @param sheetname :excel表名 resultlist:需要导出的实体数据list tablename:实体名称
*
* @throws IOException
*/

public  void exportExcel(LinkedHashMap<String, FieldFormater> map, String sheetname, HttpServletResponse response, List<?> resultlist, String entityName) throws Exception {

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(sheetname);
    HSSFRow row = sheet.createRow((int) 0);
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    int index = -1;
    for (String key : map.keySet()) {
        index=index+1;
        HSSFCell cell = row.createCell((short)index);
        cell.setCellValue(map.get(key).getColumnName());
        cell.setCellStyle(style);
    }
    Class<?> entity = Class.forName(entityName);
    Object newEntity = entity.newInstance();
    for (int i = 0; i < resultlist.size(); i++) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
        row = sheet.createRow((int) i + 1);

        newEntity = resultlist.get(i);
        int a = -1;
        for (String key : map.keySet()) {
            a = a + 1;
            row.createCell((short) a).setCellValue(map.get(key).format(entity, key, newEntity));
        }

    }
    response.setCharacterEncoding("UTF-8");
    OutputStream os = response.getOutputStream();// 取得输出流
    response.reset();// 清空输出流
    response.setContentType("application/vnd.ms-excel ");// 定义输出类型
    response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(sheetname, "UTF-8") + ".xls");// 设定输出文件头

    wb.write(os);
    os.close();
}

public interface FieldFormater{
    String format(Class<?> entity,String methodname,Object obj) throws Exception;
    String getColumnName();
}

public class DefaultFormater implements FieldFormater{
    String columnName;
    public String getColumnName() {
        return columnName;
    }
    public DefaultFormater(String columnName){
        this.columnName = columnName;

    }
    @Override
    public String format(Class<?> entity, String methodname, Object obj) throws Exception {
        Method getMethod = entity.getMethod(methodname); //得到get方法
        Type returnType = getMethod.getGenericReturnType();// 返回类型
        String value = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
        if(returnType == java.sql.Timestamp.class)
        {value = df.format(getMethod.invoke(obj));
        }else if (returnType == java.util.Date.class)
        {value = df.format(getMethod.invoke(obj));}
        else{value = getMethod.invoke(obj) + "";}
        return value;
    }
}
public class MapFieldFormater extends DefaultFormater{
    Map<String ,String> map;
    public MapFieldFormater(String columnName,Map<String ,String> map){
        super(columnName);
        this.map = map;
    }
    @Override
    public String format(Class<?> entity,String methodname,Object obj) throws Exception {
        Method getMethod = entity.getMethod(methodname); //得到get方法
        Type returnType = getMethod.getGenericReturnType();// 返回类型
        String value = getMethod.invoke(obj)+"";
        for (String key : map.keySet()) {
            if(key.equals(value))
            {
                value = map.get(key);
            }
        }
        return value;
    }
    public String getColumnName() {
        return columnName;
    }
}

}

这个是使用例子,用着特简单,什么类型的都可以,map也行
List list = countService.getCount(countId, keyName, beginDate, endDate,siteId);
LinkedHashMap map = new LinkedHashMap<>();
ExportExcelUtils exportExcelUtils = new ExportExcelUtils();
Map mm = new HashMap<>();
map.put("getKeyName", exportExcelUtils.new DefaultFormater("分类"));
map.put("getArticleCount", exportExcelUtils.new DefaultFormater("稿件数"));
map.put("getClickCount", exportExcelUtils.new DefaultFormater("点击数"));
map.put("getPraiseCount", exportExcelUtils.new DefaultFormater("点赞数"));
map.put("getCommentCount", exportExcelUtils.new DefaultFormater("评论数"));
map.put("getShareCount", exportExcelUtils.new DefaultFormater("分享数"));
map.put("getTextArticleNum", exportExcelUtils.new DefaultFormater("文章"));
map.put("getPicArticleNum", exportExcelUtils.new DefaultFormater("图集"));
map.put("getVideoArticleNum", exportExcelUtils.new DefaultFormater("视频"));
map.put("getLinkArticleNum", exportExcelUtils.new DefaultFormater("链接"));
map.put("getTopicArticleNum", exportExcelUtils.new DefaultFormater("专题"));

        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String  str = sd.format(new Date());
        String sheetName = "工作量统计" + str;
        String table = "com.zkzc.cms.count.entity.ArticleCount";
        exportExcelUtils.exportExcel(map,sheetName,response,list,table);

别忘记配置依赖包

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>

http://blog.csdn.net/mr_yangzc/article/details/75308845

<%@ page contentType="application/msexcel; charset=GBK"%>

<%
response.setHeader("Content-disposition","inline; filename=print.xls");
//以上这行设定传送到前端浏览器时的档名为print.xls

JSP导出例子,仅供参考。

public String exportXls() throws IOException {
    // 查询出 满足当前条件 结果数据
    List<WayBill> wayBills = wayBillService.findWayBills(model);

    // 生成Excel文件
    HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
    HSSFSheet sheet = hssfWorkbook.createSheet("运单数据");
    // 表头
    HSSFRow headRow = sheet.createRow(0);
    headRow.createCell(0).setCellValue("运单号");
    headRow.createCell(1).setCellValue("寄件人");
    headRow.createCell(2).setCellValue("寄件人电话");
    headRow.createCell(3).setCellValue("寄件人地址");
    headRow.createCell(4).setCellValue("收件人");
    headRow.createCell(5).setCellValue("收件人电话");
    headRow.createCell(6).setCellValue("收件人地址");
    // 表格数据
    for (WayBill wayBill : wayBills) {
        HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
        dataRow.createCell(0).setCellValue(wayBill.getWayBillNum());
        dataRow.createCell(1).setCellValue(wayBill.getSendName());
        dataRow.createCell(2).setCellValue(wayBill.getSendMobile());
        dataRow.createCell(3).setCellValue(wayBill.getSendAddress());
        dataRow.createCell(4).setCellValue(wayBill.getRecName());
        dataRow.createCell(5).setCellValue(wayBill.getRecMobile());
        dataRow.createCell(6).setCellValue(wayBill.getRecAddress());
    }

    // 下载导出
    // 设置头信息
    ServletActionContext.getResponse().setContentType(
            "application/vnd.ms-excel");
    String filename = "运单数据.xls";
    String agent = ServletActionContext.getRequest()
            .getHeader("user-agent");
    filename = FileUtils.encodeDownloadFilename(filename, agent);
    ServletActionContext.getResponse().setHeader("Content-Disposition",
            "attachment;filename=" + filename);

    ServletOutputStream outputStream = ServletActionContext.getResponse()
            .getOutputStream();
    hssfWorkbook.write(outputStream);

    // 关闭
    outputStream.close();

    return NONE;
}

System.out.println("报表数据导出");
//获取输出流
OutputStream os = response.getOutputStream();
Document doc = _dealWithDoc.CreateDoc();
Document ret = null;

        //EXCEL 导出对象
        WritableWorkbook wwb;
        try{
        /**
         * 创建sheet面板
         */
        wwb = Workbook.createWorkbook(os);

        WritableSheet ws = wwb.createSheet("汇总报表", 0);

        // 设置字体

        WritableCellFormat format14NB = DealWithExcel.getFontFormat("华文楷体",
                14, false);
        WritableCellFormat format26 = DealWithExcel.getFontFormat(
                "仿宋_GB2312", 26, false);
        WritableCellFormat format11 = DealWithExcel.getFontFormatBold(
                "宋体", 11, false);
        WritableCellFormat formatTitle = DealWithExcel.getFontFormatBoldColor(
                "华文楷体", 14,Colour.GRAY_25,false);

        String colTitle = "导出日期:"+DateBean.getBytrDate(DateBean.getSysdate()); //报表导出日期

        //添加导出日期标题
        Label labNowTime = new Label(1, 2, colTitle, format14NB);

        ws.addCell(labNowTime);

        int cols=0,rows=3; //定义行和列变量,记录行和列信息

        /**
         * 画表头
         */
        String title0 = this.getPara(request, "f_title0");//session中获取表头信息串
        String title = this.getPara(request, "f_title");//session中获取表头信息串
        String beginDate = this.getPara(request, "f_beginDate");//开始日期
        String endDate = this.getPara(request, "f_endDate");//结束日期
        String brandId = this.getPara(request, "f_breedId");//牌号信息
        String brandName = modelCenter.getBreedName(brandId);

        //将查询条件输出到报表头行
        String info = "开始日期:"+beginDate+"    结束日期:"+endDate+"     牌号:"+(brandName==null?"":brandName);
        WritableCellFormat format = new WritableCellFormat(
                format14NB);
        format.setAlignment(Alignment.LEFT); //日期,牌号信息设置顶端左对齐
        Label queryInfo = new Label(0, 0, info, format);
        ws.addCell(queryInfo);
        ws.mergeCells(0, 0, 10, 0);

        title0=unescape(title0);//解码
        title=unescape(title);//解码

        String[] titles0 = title0.split(":"); //第一行表头信息
        String[] titles = title.split(":");  //第二行表头信息
        int colBegin = 0; //记录第二行表头从第几列开始画 

        //画第一行表头
        for(int i=0;i<titles0.length;i++){
            String name1 = titles0[i].split(",")[0];//表头文字信息
            String name2 = titles0[i].split(",")[1];//表头配置信息
            Label labcolUnion = new Label(cols, rows, name1, formatTitle);
            ws.addCell(labcolUnion);
            if(name2.indexOf("rowspan")!=-1){
                String num = name2.substring(name2.indexOf("rowspan")+7);
                ws.mergeCells(cols, rows, cols, rows+new Integer(num)-1);
            }else if(name2.indexOf("colspan")!=-1){
                if(colBegin==0) colBegin = cols; //记录第二行表头从第几列开始画 
                String num = name2.substring(name2.indexOf("colspan")+7);
                ws.mergeCells(cols, rows, cols+new Integer(num)-1, rows);
                cols=cols+new Integer(num)-1; 
            }
            cols++;
        }
        rows++;

        //画第二行表头
        for(int i=0;i<titles.length;i++){
            Label labcolUnion = new Label(colBegin, rows, titles[i], formatTitle);
            ws.addCell(labcolUnion);
            colBegin++;
        }
        rows++;

        String urlPath=this.getPara(request, "url_path"); //取得路径

        List obj = null ;//数据对象集合

        int round = 1;
        do{

        //设置一次查询的记录最多为10000条
        request.setAttribute("limit","10000");
        request.setAttribute("start",(10000*(round++-1))+"");   
        //根据urlPath的值判断是哪个页面的数据导出
        if(urlPath.equals("SpecialProAcc")){
            ret=new SpecialProAcc(request).Document;
        }else if (urlPath.equals("ProExpQuaRate")){
            ret=new ProExpQuaRate(request).Document;
        }
        // 开始打印

// DebugOut.println(ret.asXML());
ret = DealWithWebDoc.deleteBlankElement(ret);

        //打印到控制台
        DebugOut.println(ret.asXML());

        ConvertXml cvt = new ConvertXml();

        //获取数据成功标志 true 则表示数据获取成功,false则相反
        Attribute attribute = (Attribute)ret.selectNodes("/dataset/response/@success").get(0);
        Boolean success = new Boolean(attribute.getValue());
        //去掉response中success属性  如果不去除 转换成pojo时程序会出错
        Element el = (Element)ret.selectNodes("/dataset/response").get(0);
        el.remove(attribute);
        /**
         * 开始导出数据
         */
        //如果数据获取成功则导出数据
            if(success){
                String docStr = ret.asXML();
                String pojoName = null;

                if ((pojoName = cvt.getClassNameFromXml(docStr)) != null) {

                    obj = (List)cvt.ConvertList(docStr);// 将xml串转成对象
                    /**
                     * 导出数据
                     */
                    rows=dataOut(request,ws,obj,rows,format11);
                    //....
                }

            }}while(obj!=null&&obj.size()==10000);


            String filename = this.getPara(request, "f_filename");
            filename=unescape(filename);//解码

            Label labTitle = new Label(0, 1, filename, format26);
            ws.addCell(labTitle);// 设置标题

            ws.mergeCells(0, 1, cols-1, 1);// 标题行,合并最大列

// System.out.println("MAXLENGTH***************************"+maxLength);
//

// maxLength = maxLength==0?13:(int)(maxLength*1.7); //默认设置列宽为13
//设置列宽
for(int i=0;i<cols;i++){
if(i==1) ws.setColumnView(i, 18);
else ws.setColumnView(i, 12);
}

            String dateStr = filename+"报表_导出数据" + DateBean.getSysdateTime()
                    + ".xls";
            String fileName = new String(dateStr.getBytes("GBK"), "iso-8859-1");
            response.setContentType("application/x-octetstream;charset=gb2312");
            response.setHeader("Content-disposition", "attachment;filename="
                    + fileName + "");

            wwb.write();
            os.flush();
            wwb.close();
            os.close();
            response.flushBuffer();

        }catch(Exception e){
            e.printStackTrace();//追踪错误定位
        }