如何使用Servlet在特定单元格的Excel工作表中写入数据?

时间:2019-06-25 08:46:23

标签: java excel servlets

我是Servlet的新手,请帮助我。我创建了一个Servlet文件,其中一个Excel文件包含来自用户的一些数据。数据通过字符串打印。现在,大多数数据均按预期进行打印,但是现在我想在excel工作表的特定单元格中以特定格式打印存储的数组数据。请参考所提供的照片,了解我期望的格式。并参考我的代码以获得更好的理解。主要目标是在Excel工作表的特定单元格中打印存储的数组数据。请帮助我编写代码,因为我真的是Servlet的新手。请参阅此 link

testExcel

@WebServlet("/testExcel")
public class testExcel extends HttpServlet {

    private static final long serialVersionUID = 1L;
    String emails = "xyz@gmail.com";

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

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        OutputStream writer = response.getOutputStream();
//        FileWriter writer =null;
        ResultSet rs = null;
        ResultSet rs1 = null;
        Connection con = null;
        ArrayList data_ar = new ArrayList();
        String str = "";
        PreparedStatement ps = null;
        PreparedStatement ps1 = null;
        try {
            String fileName = emails + "data.csv";
            System.out.println(fileName);
            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);
            ConnectionClass cn = new ConnectionClass();
            con = cn.connectDb();

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

            //Write the CSV file header
            CSVUtil.writeLine(writer, Arrays.asList("NAME", "email", "  ", "  ", "  ", "NAME AND EMAIL"));
            ps = con.prepareStatement("select name,email from user");
            rs = ps.executeQuery();
            ps1 = con.prepareStatement("select name,email from user");
            rs1 = ps1.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getString("name"));
                CSVUtil.writeLine(writer, Arrays.asList(rs.getString("name"), rs.getString("email")));
            }
            while (rs1.next()) {
                data_ar.add(rs1.getString("name") + "     " + rs1.getString("email") + "\n");

            }
            str = String.join(" ", data_ar);
            CSVUtil.writeLine(writer, Arrays.asList("  ", "  ", "  ", "  ", "  ", str));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                ps.close();
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

csvutil.java

public class CSVUtil {

private static final char DEFAULT_SEPARATOR = ',';

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

public static void writeLine(OutputStream 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(OutputStream 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");
    String str = sb.toString();
    byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
    w.write(bytes);

}

}

1 个答案:

答案 0 :(得分:-1)

简单快速的答案:

您应该尝试使用Apache POI

Maven依赖性:

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.15</version>
</dependency>

一个简单的类,可在excel文件中写入列表:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ApachePOIExcelWrite {

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main(String[] args) {

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
        Object[][] datatypes = {
                {"Datatype", "Type", "Size(in bytes)"},
                {"int", "Primitive", 2},
                {"float", "Primitive", 4},
                {"double", "Primitive", 8},
                {"char", "Primitive", 1},
                {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");

        for (Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if (field instanceof String) {
                    cell.setCellValue((String) field);
                } else if (field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            workbook.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Done");
    }
}