簡體   English   中英

如何使用servlet在特定單元格的excel表中寫入數據?

[英]How to write data in excel sheet in specific cell using servlet?

我是 Servlet 的新手,請幫助我。 我創建了一個 Servlet 文件,其中一個 excel 文件包含來自用戶的一些數據。 數據通過字符串打印。 現在,大部分數據都按照預期打印,但現在我想在 Excel 工作表的特定單元格中以特定格式打印數組存儲的數據。 請參閱提供的照片以了解我所期望的格式。 並參考我的代碼以獲得更好的理解。 主要目標是在excel表的特定單元格中打印數組存儲的數據。 請幫助我編寫代碼,因為我對 Servlet 非常陌生。 參考這個鏈接

測試Excel

@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);

}

}

簡單快速的回答:

您應該嘗試使用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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM