- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我曾尝试在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+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYw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zY4REFDIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjcyNzU3Q0UwMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIi8+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/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!