gpt4 book ai didi

java - 如何使用servlet jsp读取excel文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:33 26 4
gpt4 key购买 nike

我曾尝试在apache tomcat中将excel文件从jsp读取到servlet。下面的代码在写入文件并获取该文件后已从apache文件夹接收excel文件。我不需要在apache tomcat中写入。如何直接读取excel文件值。以下代码是MyServletUpload.java。

  import java.io.BufferedReader; 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
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 com.mysql.jdbc.Statement;
import com.ppts.webwatcher.Validation.Urlvalidation;
import com.ppts.webwatcher.setting.DBConnector;
import com.ppts.webwatcher.webdownload.Webpagedownload;


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

private static final long serialVersionUID = 1L;

private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;

/**
* @see HttpServlet#HttpServlet()
*/
public MyservletUpload() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
int count = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection con = db2Connector.getConnection(true);
Statement stmt = null;
String compName = null;
String url_Name = null;
String message = null;
if (!isMultipart) {
return;
}

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);

// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("/");
// + File.separator + DATA_DIRECTORY;

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);

try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println("file path : " + filePath);
item.write(uploadedFile);

FileInputStream fis = new FileInputStream(uploadedFile);

XSSFWorkbook workbook = new XSSFWorkbook(fis);

// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);

// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
String h = "";
int i = 1;
while (cellIterator.hasNext()) {

Cell cell = cellIterator.next();
// Check the cell type and format accordingly

switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
if (i == 1) {
h = cell.getStringCellValue();
} else {
h = h + "~" + cell.getStringCellValue();
}

i++;
}

String[] a = h.split("~");
compName = a[0].trim();
url_Name = a[1].trim();
System.out.println("company name : " + compName);
System.out.println("ulr name : " + url_Name);
try {
long ft1 = 0;
long ft2 = 0;
int lk = 0;

BufferedReader in = null;
BufferedWriter be = null;
String filenam = "";

String patr = getServletContext().getRealPath("/");
filenam = patr + "webfolder";
// System.out.println("part : " + filenam);
File filchkr = new File(filenam);
if (filchkr.exists()) {
// System.out.println("fil exists");
} else {
// System.out.println("fil not exists");
}

try {

ft1 = System.currentTimeMillis();
String line1;
// String arrsp =
// "http://www.mmrf.org/research/research.html~helwel131";

int li = compName.length();

// System.out.println("Urlname " + url_Name);

// System.out.println("companyname " +
// compName);

System.out.println("@@@@"
+ Urlvalidation.checkInsertValidation(
url_Name, compName));

if (Urlvalidation.checkInsertValidation(
url_Name, compName) != null) {

System.out
.println("error url name >>>>>>>>> "
+ url_Name);
System.out
.println("errror url link >>>>>>>>>>>"
+ compName);

} else {

String urlreplaceText = url_Name.replace(
" ", "%20");
// System.out.println("path : "+getServletContext().getRealPath("/"));
URL url1 = new URL(urlreplaceText);
// System.out.println(url1);
String filepath = filenam + "/" + compName;
File f1 = new File(filepath);

if (!f1.exists()) {
}
boolean result = false;

try {
f1.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
String fullpath = filepath
+ "/firstdownload.html";

Webpagedownload.webdown(fullpath, url1);

lk = 1;
ft2 = System.currentTimeMillis();

long ft = ft2 - ft1;
// System.out.println(ft + ": time ");

String selection = "full_content";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(
DATE_FORMAT);
String strDateNew = sdf.format(now);
stmt = (Statement) con.createStatement();
String sql = "INSERT INTO new_table (title,url,source_selection,content,inserttime,insertvalue) VALUES ('"
+ compName
+ "','"
+ url_Name
+ "','"
+ selection
+ "','','"
+ strDateNew + "','" + '0' + "')";
stmt.executeUpdate(sql);
HttpSession session = request.getSession();
String username = String.valueOf(session
.getAttribute("username"));
String userid = String.valueOf(session
.getAttribute("userid"));

stmt.executeUpdate("insert into usersession(userid,username,createtime,urlname,urllink) values('"
+ userid
+ "','"
+ username
+ "','"
+ strDateNew
+ "','"
+ compName
+ "','" + url_Name + "')");

}

} catch (Exception e) {
System.out.println("Error: \t" + e);
System.out
.println("exception Urlname>>>>>>>>> "
+ url_Name);
System.out
.println("exception companyname >>>>>>>>>>>"
+ compName);
}

} catch (Exception e) {
System.out.println(e);
}
count++;

}

message = "success";
File file = new File(filePath);

file.delete();

}
}

getServletContext().getRequestDispatcher("/Message.jsp").forward(
request, response);

} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}

}

  jsp 
<form method="post" action="MyservletUpload"
enctype="multipart/form-data">
Choose File : <input type="file" name="photo" size="50" /> <input
type="submit" value="Upload" onclick="uppload()">


</form>



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*,java.util.*,java.io.*"%>
<%@ page import="com.ppts.webwatcher.setting.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>



<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>




<script type="text/javascript">

function Pager(tableName, itemsPerPage) {

this.tableName = tableName;

this.itemsPerPage = itemsPerPage;

this.currentPage = 1;

this.pages = 0;

this.inited = false;

this.showRecords = function(from, to) {

var rows = document.getElementById(tableName).rows;

// i starts from 1 to skip table header row

for (var i = 1; i < rows.length; i++) {

if (i < from || i > to)

rows[i].style.display = 'none';

else

rows[i].style.display = '';

}

}

this.showPage = function(pageNumber) {

if (! this.inited) {

alert("not inited");

return;

}

var oldPageAnchor = document.getElementById('pg'+this.currentPage);

oldPageAnchor.className = 'pg-normal';

this.currentPage = pageNumber;

var newPageAnchor = document.getElementById('pg'+this.currentPage);

newPageAnchor.className = 'pg-selected';

var from = (pageNumber - 1) * itemsPerPage + 1;

var to = from + itemsPerPage - 1;

this.showRecords(from, to);

}

this.prev = function() {

if (this.currentPage > 1)

this.showPage(this.currentPage - 1);

}

this.next = function() {

if (this.currentPage < this.pages) {

this.showPage(this.currentPage + 1);

}

}

this.init = function() {

var rows = document.getElementById(tableName).rows;

var records = (rows.length - 1);

this.pages = Math.ceil(records / itemsPerPage);

this.inited = true;

}

this.showPageNav = function(pagerName, positionId) {

if (! this.inited) {

alert("not inited");

return;

}

var element = document.getElementById(positionId);

var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';

for (var page = 1; page <= this.pages; page++)

pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';

pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';

element.innerHTML = pagerHtml;

}

}

</script>
<SCRIPT language="javascript">
$(function(){

// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});

// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){

if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}

});
});
</SCRIPT>

<style>
.textbox {
background:
url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABClpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gP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UwMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+SoKR9AAAAH5JREFUeNpi/P//PwMlgImBQsDS39/fAKTrydTfyESBZhCoR/bCAig9AYgZceAFaGpRwiARKlEAxPOx2AYSS4CqSYSHAZoimEQCGh+rZmwGYDOEAZdmXAZgMwSrZnwGMKBpSMSZDghEUyLtUyIS+z+5eaGRAgc0Mg54bgQIMAAD7RsCMDpK7QAAAABJRU5ErkJggg==)
no-repeat 10px 4px #FFF;
height: 25px;
width: 275px;
border: 1px solid #848484;
padding-left: 30px;
}
</style>


<title>UPDATE SCANNER-Updated Url</title>
</head>
<%@ include file="header.jsp"%>
<body>
<SCRIPT language="JavaScript">
function OnSubmitForm()
{
if(document.pressed == 'Send Email')
{
document.myform.action ="emailaction.jsp";

}
else
if(document.pressed == 'View')
{


var slvals = [];
$('input:checkbox[name=case]:checked').each(function() {
slvals.push($(this).val());

});
var i;
for (i = 0; i < slvals.length; i++) {
var url="Multitabhelp.jsp?urlid="+slvals[i];
var win = window.open(url, '_blank');
win.focus();
}

return false;


}
return true;
}
</SCRIPT>
<center>
<b><h1>Updated URL</h1> </b>


<FORM name="myform" onSubmit="return OnSubmitForm();">
<%
int co = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection conn = db2Connector.getConnection(false);
Statement stmt = null;
Statement stmt1 = null;
String time;
String urld = request.getParameter("urlid");
System.out.println("hello " + urld);
try {

stmt = conn.createStatement();
stmt1 = conn.createStatement();
String son = "";
String b = "";
String sww = "select * from updatehistory where updatetime='"
+ urld + "' and updation='1'";
System.out.println(sww);
ResultSet rs = stmt
.executeQuery("select * from updatehistory where updatetime='"
+ urld + "' and updation='1'");
out.println("<div class='CSSTableGenerator'>");
out.println("<TABLE BORDER=1 id=\"tablepaging\" class=\"yui\" align=\"center\">");
out.println("<th>"
+ " S.No"
+ "</th>");
out.println("<th>"
+ " Date"
+ "</th>");
out.println("<th>"
+ " Source Name"
+ "</th>");
out.println("<th>"
+ " URL"
+ "</th>");
out.println("<th>"
+ " Updated Content"
+ "</th>");
%>
<th><input type="checkbox" id="selectall" /></th>
<%
out.println("<th>"
+ " <label class='col-md-3 control-label'> Action</label>"
+ "</th>");
while (rs.next()) {

time = rs.getString("date_time");

ResultSet rs11 = stmt1
.executeQuery("select * from new_table where urlid='"
+ rs.getString("urlid") + "' ");
if (rs11.next()) {
System.out.println(rs11.getInt(1));
out.println("<TR>");

out.println("<TD>" + co + "</TD>");
out.println("<TD>" + rs.getString("date_time")
+ "</TD>");
out.println("<TD>" + rs11.getString("title")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("url")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("updatecontent")
+ "</a></TD>");
%>
<td><input type="checkbox" class="case" name="case" id="chease"
value="<%=rs.getString("urlid")%>"></td>
<%
out.println("<TD><a href=\"Showupdate.jsp?urlid="
+ rs.getString("urlid") + "\" >VIEW </a></TD>");
}
%>






<%
out.println("</TD>");

out.println("</TR>");
co++;

}
out.println("</TABLE>");
if (co < 2) {
System.out.println("************" + co);
out.println("<center> NO UPDATES </center>");
}

out.print("</div");
} finally {
try {

conn.close();
} catch (SQLException se) {
}
}
%>


<br> Enter Email ID : <input type="text" class="textbox"
name="email"> <INPUT TYPE="SUBMIT" name="Operation"
onClick="document.pressed=this.value" VALUE="Send Email"> <br>
<br> <br> Click to View Selected Update Link... <INPUT
TYPE="SUBMIT" name="Operation" onClick="document.pressed=this.value"
VALUE="View">
</FORM>
<br> <br>
<div id="pageNavPosition" style="padding-top: 20px" align="center">
</div>
<br>
</center>
<script type="text/javascript"><!--
var pager = new Pager('tablepaging', 10);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
</script>


<%@ include file="footer.jsp"%>
</body>
</html>

最佳答案

如果您不使用 maven,最好使用 Apache POI 并做一件事,下载以下 jar 并将其保存在您的 lib 中

dom4j-1.6.1.jar,poi-3.9-20121203.jar,poi-ooxml-3.9-20121203.jar,poi-ooxml-schemas-3.9-20121203.jar,xmlbeans-2.3.0.jar

然后使用一些类,您可以读取 Excel 文件,甚至可以逐行或单元格读取

试试这个,希望这对你有用......

关于java - 如何使用servlet jsp读取excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26058178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com