在按钮单击时从用户读取xls文件内容

时间:2014-08-05 12:40:00

标签: java excel jsp

我想允许用户上传xlsx文件。这将是特定的格式。

然后我想阅读xls文件的内容并想插入数据库。

这里我采用绝对文件路径来读取和插入数据。

如何从用户那里读取文件并执行我已执行的操作?

public class upload {
    public static void main(String[] args) throws IOException, SQLException {
        Myconnection con = new Myconnection();
        Statement stmt = null;
        FileInputStream fis = new FileInputStream(new File("C:/upload.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook (fis);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator ite = sheet.rowIterator();

        //PreparedStatement prepStmt = con.getConnection().prepareStatement("insert into ParcelCoordinates(Subdivision,ParcelNo,PointID,Easting,Northing,Height) values (?,?,?,?,?,?)");
        String prepStmt = "insert into ParcelCoordinates(RequestID,SubdivisionNo,ParcelNo,PointID,Easting,Northing,Height) values (?,?,?,?,?,?,?)";
        PreparedStatement ps = con.getConnection().prepareStatement(prepStmt); 

...remaining code 

}

我把提交按钮和按钮点击用户上传文件

<form:form action="" modelAttribute="uploadFile" name="uploadRequest">      
                    <div align="center" style="margin-bottom: 10px;">
                        <button onClick = "downloadTemplate()"  style="width:250px" type="submit" class="admin_search_btn"><spring:message code="lblDownloadXls"></spring:message></button>
                    </div>
                    <div align="center" style="margin-bottom: 10px;" >
                        <form:input path="fileName" style="width:200px" class="admin_search_btn" type="file" name="uploadxls" value="" />
                        <!-- <input style="width:200px" class="admin_search_btn" type=file name="uploadxls" value=""  /> -->
                    </div>
                    <div align="center" style="margin-bottom: 10px;" >  
                        <button onClick = "uploadTemplate()" type="submit" class="admin_search_btn"><spring:message code="lblSubmit"></spring:message></button>&nbsp;
                        <button  type="submit" class="admin_search_btn"><spring:message code="lblCancel"></spring:message></button>
                    </div>
                </form:form>     

现在我该如何阅读用户上传的文件?

1 个答案:

答案 0 :(得分:-1)

此链接将向您展示如何触发点击操作:http://www.javamex.com/tutorials/swing/jbutton.shtml

由于xls是一个文本文件,你可以用:

来读取它
BufferedReader br = new BufferedReader(new FileReader("C:/upload.xlsx"));
String line;
while ((line = br.readLine()) != null) {
    // process the line.
}
br.close();

在流程线中,您可以进行拆分和替换,以获得您想要的结果。