Uploading Excel File Using Jsp

There are two choice for reading and writing the Excel file in your application.

1.By Using the JExcelapi

2.By Jakarta’s Poi.jar which uses the HSSFSheet read and write.

–> Using the JExcelapi which  is  not suitable for the important data. It fails to read several files and  in most occasions it also fails to create cells. In short JExcelAPI isn’t suitable for enterprise use.

–>Where as the POI.jar is a Jakarta  Project’s which was developed  by pure Java implementation of the Excel file format. It is a mature product and was able to correctly and effortlessly read excel data generated from various sources, including non-MS Excel products like Open Office, and for various versions of Excel. so for this reasons it is Highly recommended.

Before Using this Code you have to download the poi.jar file  and place it in the lib folder of your application (or) place in the jar folder and give the path in the environment variables in the My Computers, and then import the HSSF files and then follow the code

<%@ page import = “java.io.*” %>
<%@ page import = “java.sql.*” %>
<%@ page import = “javax.servlet.*” %>
<%@ page import = “javax.servlet.http.*” %>
<%@ page import = “java.util.*” %>
<%@ page import = “java.awt.*” %>
<%@ page import = “java.io.File” %>
<%@ page import = “java.io.IOException” %>
<%@ page import = “javax.swing.filechooser.FileSystemView” %>

<%@ page import=”org.apache.poi.hssf.usermodel.HSSFSheet”%>
<%@ page import=”org.apache.poi.hssf.usermodel.HSSFWorkbook”%>
<%@ page import=”org.apache.poi.hssf.usermodel.HSSFRow”%>
<%@ page import=”org.apache.poi.hssf.usermodel.HSSFCell”%>

<%
//Here Datedas is the value of the length which is retrived from the database in my application


String fname1=”File”-”+Datedas+”.xls”;

//Giving name to the file

//creating a file object

File fname=new File(fname1);

//Creating an object to the HSSF Class

HSSFWorkbook hwb = new HSSFWorkbook();

//Giving the name to the Excel file which will be created by this HSSFsheet

HSSFSheet sheet = hwb.createSheet(“stock sheet”);

//Creating the row for your data

HSSFRow pw = sheet.createRow((short)2);

//Mention the Heading of your Excel sheet

pw.createCell((short) 0).setCellValue(“S.No”);
pw.createCell((short) 1).setCellValue(“Heading1″);
pw.createCell((short) 2).setCellValue(“
Heading2“);
pw.createCell((short) 3).setCellValue(“
Heading3“);
pw.createCell((short) 4).setCellValue(“
Heading4“);
pw.createCell((short) 5).setCellValue(“
Heading5“);
pw.createCell((short) 6).setCellValue(“
Heading6“);
pw.createCell((short) 7).setCellValue(“
Heading7“);
pw.createCell((short) 8).setCellValue(“
Heading8“);
pw.createCell((short) 9).setCellValue(“
Heading9“);
pw.createCell((short) 10).setCellValue(“
Heading10“);
pw.createCell((short) 11).setCellValue(“
Heading11″);

//String stored1=”",stored2=”",stored3=”",stored4=”",stored5=”",stored6=”",stored7=”",stored9=”";
//float stored8=0.0f,stored10=0.0f,stored12=0.0f;
int comprk=1;

int index=3;
//int compno=0;
int sno=0;
while(rs.next())
{

compno=1;
sno++;

System.out.println(“Testing in the loop  “+compno);

//Creating the Excel Sheet Rows

HSSFRow row = sheet.createRow((short)index);

row.createCell((short) 0).setCellValue(sno);

row.createCell((short)                                                    .setCellValue(Integer.parseInt(rs.getString(1)));
row.createCell((short) 2).setCellValue(rs.getString(2));
row.createCell((short) 3).setCellValue(rs.getString(3));
row.createCell((short) 4).setCellValue(rs.getString(4));
row.createCell((short) 5).setCellValue(rs.getString(5));
row.createCell((short) 6).setCellValue(rs.getString(6));
row.createCell((short) 7).setCellValue(rs.getString(7));
row.createCell((short) 8).setCellValue(rs.getFloat(8));
row.createCell((short) 9).setCellValue(rs.getString(9));
row.createCell((short) 10).setCellValue(rs.getFloat(10));
row.createCell((short) 11).setCellValue(rs.getFloat(13));
index++;
}

FileOutputStream fileOut = new FileOutputStream(fname);

hwb.write(fileOut);
fileOut.flush();
fileOut.close();
out.println(“<b>Your excel file has been Successfully generated</b>”);

%>

 

Find More file upload examples click here 1 , 2 and 3

Uploading file name or image to DataBase

This is an example of the file Uploading in Java using Servlets . This file uploading concept Works with the Java as follows

Here is the Code of the file Uploading using Servlets in JAVA and saving the image and filename of image in the database

Name the HTML page as file.html

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<form method=”post” action=”servlet/UploadFile” enctype=”multipart/form-data”>
Name
<input type=”text” name=”uname”/>
File
<input type=”file” name=”upfile”/>
<input type=”submit”/>
</form>
</html>

Write the servlet code and specify the name of the servlet as UploadFile.java

package com.struts;

import java.io.*;
import java.sql.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletInputStream.*;
import java.io.PrintWriter;

public class UploadFile extends HttpServlet {

public void doPost(HttpServletRequest req,HttpServletResponse res)
{

try{

Class.forName(“com.mysql.jdbc.Driver”);
Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost/test?user=root&password=test”);
PrintWriter out=res.getWriter();

//out.println(“<br>Content type is :: ” +contentType);
//to get the content type information from JSP Request Header
String contentType = req.getContentType();
int flag=0;
FileInputStream fis=null;
FileOutputStream fileOut=null;
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
if ((contentType != null) && (contentType.indexOf(“multipart/form-data”) >= 0))
{
DataInputStream in = new DataInputStream(req.getInputStream());
//we are taking the length of Content type data
int formDataLength = req.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;

//this loop converting the uploaded file into byte code
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}

String file = new String(dataBytes);
//for saving the file name
String saveFile = file.substring(file.indexOf(“filename=\”") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf(“\n”));
out.println(“savefiledddd    “+saveFile);
int extension_save=saveFile.lastIndexOf(“\”");
String extension_saveName=saveFile.substring(extension_save);

//Here we are invoking the absolute path out of the encrypted data

saveFile = saveFile.substring(saveFile.lastIndexOf(“\\”)+ 1,saveFile.indexOf(“\”"));
int lastIndex = contentType.lastIndexOf(“=”);
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;

//extracting the index of file
pos = file.indexOf(“filename=\”");
pos = file.indexOf(“\n”, pos) + 1;
pos = file.indexOf(“\n”, pos) + 1;
pos = file.indexOf(“\n”, pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) – 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

out.println(“savefile”+saveFile);

int file_No=22;
String pathname_dir=”D:\\rk\\”+saveFile;
File filepath=new File(pathname_dir);
out.println(“filepath_  “+filepath);
fileOut = new FileOutputStream(filepath);
fileOut.write(dataBytes, startPos, (endPos – startPos));
fileOut.flush();
out.println(“<h1> your files are saved</h1></body></html>”);
out.close();

File database_filename=new File(pathname_dir);
fis=new FileInputStream(database_filename);
PreparedStatement ps = conn.prepareStatement(“insert into test (fname) values (?)”);
ps.setString(1,database_filename.getName());
ps.executeUpdate();
ps.close();
flag=1;

}

if(flag==1)
{
fileOut.close();
fis.close();
}
}catch(Exception e)
{
System.out.println(“Exception Due to”+e);
e.printStackTrace();
}
}
}

The above code is used to save the path in the DataBase where(in Which directory/folder) the file is saved .

If you want to save the image into data base the just modify the part of the above code like the below specified.

Here note that the image column data type should be take as blob

File database_filename=new File(pathname_dir);
fis=new FileInputStream(database_filename);
PreparedStatement ps = conn.prepareStatement(“insert into test (fname,image) values (?,?)”);
ps.setString(1,database_filename.getName());
ps.setBinaryStream(2,fis,database_filename.length())

//ps.setBinaryStream(int parameterIndex,InputStream x,int length)

to know more about BinaryStream and the methods of sql package clickhere
ps.executeUpdate();
ps.close();

Here is Deployment discriptor to pass the request from the html to Servlet program. save these with the name web.xml in the WEB-INF directory

<servlet>
<servlet-name>UploadFile</servlet-name>
<servlet-class>com.myapp.struts.UploadFile</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UploadFile</servlet-name>
<url-pattern>/servlet/UploadFile</url-pattern>
</servlet-mapping>

 

Find More file upload examples click here 1 , 2 and 3

Creating a Text file using Java

//Write a java program for creating a text file

import java.io.*;
import java.io.OutputStream;

class FileAccess
{
public static void main(String args[])throws IOException
{

//Attach keyboard to DataInputStream

DataInputStream dis=new DataInputStream(System.in);

//Attach myfile to fileoutputstream

FileOutputStream fos=new FileOutputStream(“xxxx.txt”);

//read data from datainputstream and write it into fileoutputstream

ObjectOutputStream p=new ObjectOutputStream(fos);
char ch;
System.out.println(“Enter date(@ to end the program);”);
while((ch=(char)dis.read())!=’@')
fos.write(ch);
p.writeInt(12345);
p.writeObject(“Today”);
p.putFields();

//p.writeStreamHeader();

p.writeFields();

p.flush();

//closefikle

fos.close();
}
}

Procedure:

First compile the program and run the program then given the inputs as a string then exit that and u can fine the file in the destination u had specified

Explain Stream Tokenizer

Stream Tokenizer :

StreamTokenizer is a direct subclass of Object class. StreamTokenizer is included in java.io. Package. The StreamTokenizer class takes an input stream and parses it into “tokens” , allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags ( like TT_WORD, TT-EOF,TT-EOL etc., all representing some integer value) that can be set to various states. The StreamTokenizer can recongnize identifiers, numbers, quoted strings and various comment styles. Tokenizing is a feature of compilers, interpreters and parsers.

A stream can contain three types of tokens.

  • Words ( that is, multiple character tokens )
  • Single-character tokens
  • Whitespace( including C/C++/Java-style comments )

Some constants, defined in StreamTokenizer, used as flags to identity the tokens :

int TT-EOL : A constant indicating that the end of the line has been read.

Int TT-EOF : A constant indicating that the end of the stream has been read.

int TT-WORD : A constant indicating that a word token has been read.

Int ttype : After a call to the nextToken method, this field contains the type of the token just read

Aim : To count the number of words in a file using StreamTokenizer and whitespace as delimiter File name is passes as command-line argument.

Sample program of StreamTokenizer as follows :

import java.io.*
public class StreamTokenizerDemo {
static int words = 0;
public static void wordCount(Reader r)throws IOException
{
StreamTokenizer st = new StreamTokenizer(r);
st.wordChars(33,255);

// if token in not EOF
while(st.nextToken()!=st.TT_EOF)
{
//if token is word
if(st.ttype == st.TT_WORD)
words++;
}

}
public static void main(String args[])throws IOException
{
// pass file name as command-line
FileReader fr = new FileReader(args[0]);
wordCount(fr);
System.out.pritnln(” Total words in file :”+words);
}
}

Method signature of wordChars();

public void wordChars(int low, int high);

Specifies that all characters between thew range low and high are word constituents. A word token consists of a word constituent followed by zero or more word constituents or number constituents