将数据写入excel(CSV)文件

时间:2019-06-07 05:53:36

标签: java servlets

我创建了一个servlet代码。主要目标是将数据从数据库写入csv文件。在我的代码中,csv文件已成功下载,但该文件仍然为空。该项目包含javacsv.jar文件。我不知道为什么会这样。请阐明我如何实现这一目标。有关摘要,请阅读以下几点:

  • 访问数据库表中的数据。
  • 然后将数据以表格式(如 data here )写入csv文件。 [我想要这种格式,因为我可以根据需要格式化该数据。]
  • 请让大家放松一下:)请参阅下面的Servlet代码:
public class excelServletFile extends HttpServlet {

    String name = "";
    String email = "";
    String eid = "Username";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            String fileName = eid + "Data.csv";
            ServletContext context = getServletContext();
            String mimeType = context.getMimeType(fileName);
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }
            response.setContentType(mimeType);
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", fileName);
            response.setHeader(headerKey, headerValue);
            OutputStream outStream = response.getOutputStream();
            ConnectionClass cn = new ConnectionClass();
            Connection con = cn.connectDb();
            PreparedStatement ps;
            ResultSet rs;
            Charset cs = Charset.forName("UTF-8");
            Writer writer = new PrintWriter(System.out);
             writer.flush();
            writer.append("NAME");
            writer.append("EMAIL");
            ps = con.prepareStatement("select name,email from user");
            rs = ps.executeQuery();

            while (rs.next()) {
                name = rs.getString("name");
                email = rs.getString("email");
                PrintWriter out = response.getWriter();
                out.println(name);
                out.println(email);
                writer.append(name);
                writer.append(email);

            }

            writer.close();
        } catch (Exception e) {
            System.out.println(e);
        }
}

1 个答案:

答案 0 :(得分:1)

package servletProject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/govinds")
public class CSVServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        FileWriter writer = null;
        ResultSet rs = null;
        Connection con = null;
        PreparedStatement ps = null;
        try {
            String fileName = "D:/Data.csv";
            System.out.println(fileName);

            ConnectionClass cn = new ConnectionClass();
            con = cn.connectDb();

            System.out.println("fileName" + fileName);

            writer = new FileWriter(fileName);
            // Write the CSV file header
            CSVUtils.writeLine(writer, Arrays.asList("NAME", "email"));
            ps = con.prepareStatement("select firstName,email from employees");
            rs = ps.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getString("firstName"));
                CSVUtils.writeLine(writer, Arrays.asList(rs.getString("firstName"), rs.getString("email")));

            }

            writer.flush();
            writer.close();

            download(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                ps.close();
                con.close();
            } catch (Exception e) {
            }
        }
    }

    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = "D:/Data.csv";
        File downloadFile = new File(filePath);
        FileInputStream inStream = new FileInputStream(downloadFile);

        // if you want to use a relative path to context root:
        String relativePath = getServletContext().getRealPath("");
        System.out.println("relativePath = " + relativePath);

        // obtains ServletContext
        ServletContext context = getServletContext();

        // gets MIME type of the file
        String mimeType = context.getMimeType(filePath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // modifies response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // forces download
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName() + ".csv");
        response.setHeader(headerKey, headerValue);

        // obtains response's output stream
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[4096];
        int bytesRead = -1;

        while ((bytesRead = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        inStream.close();
        outStream.close();
    }
}

//数据库连接文件

 public class ConnectionClass {


        public Connection connectDb() {

            Connection con=null;
            try {
                Class.forName("com.mysql.jdbc.Driver");  
                 con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");  
            }catch (Exception e) {
                con=null;
            }

            if(con!=null)
                System.out.println("connected");
            else
                System.out.println("not connected");

            return con;
        }
    }

// CSVUtil文件

package servletProject;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class CSVUtils {

    private static final char DEFAULT_SEPARATOR = ',';

    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');
    }

    // https://tools.ietf.org/html/rfc4180
    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }

    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        // default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            if (customQuote == ' ') {
                sb.append(followCVSformat(value));
            } else {
                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
            }

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());
    }

}