❶ java怎麼導出excel表格
可以使用POI開源的api:
1.首先下載poi-3.6-20091214.jar,下載地址如下:
http://download.csdn.net/detail/evangel_z/3895051
2.Student.java
import java.util.Date;
public class Student
{
private int id;
private String name;
private int age;
private Date birth;
public Student()
{
}
public Student(int id, String name, int age, Date birth)
{
this.id = id;
this.name = name;
this.age = age;
this.birth = birth;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public Date getBirth()
{
return birth;
}
public void setBirth(Date birth)
{
this.birth = birth;
}
}
3.CreateSimpleExcelToDisk.java
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CreateSimpleExcelToDisk
{
/**
* @功能:手工構建一個簡單格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Student user1 = new Student(1, "張三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
public static void main(String[] args) throws Exception
{
// 第一步,創建一個webbook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("學生表一");
// 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,創建單元格,並設置值表頭 設置表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("學號");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("年齡");
cell.setCellStyle(style);
cell = row.createCell((short) 3);
cell.setCellValue("生日");
cell.setCellStyle(style);
// 第五步,寫入實體數據 實際應用中這些數據從資料庫得到,
List list = CreateSimpleExcelToDisk.getStudent();
for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,創建單元格,並設置值
row.createCell((short) 0).setCellValue((double) stu.getId());
row.createCell((short) 1).setCellValue(stu.getName());
row.createCell((short) 2).setCellValue((double) stu.getAge());
cell = row.createCell((short) 3);
cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
.getBirth()));
}
// 第六步,將文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/students.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
❷ java如何另存導出Excel
1./**
* 出險信息導出到excel(fc)
* @param mapping
* @param form
* @param request
* @param response
* @throws IOException
*/
public void exportActoExcel(ActionMapping mapping, ActionForm form ,
HttpServletRequest request,HttpServletResponse response) throws IOException {
ActionErrors errors = new ActionErrors();
AcExcelBusi acBusi = new AcExcelBusi();
AccidentRecordForm arForm= (AccidentRecordForm) form;
AccidentRecordBusi arBusi = new AccidentRecordBusi();
// ////查詢條件
FwUsers sessUser = (FwUsers)request.getSession().getAttribute(ConstValues.SESS_USER_MANAGE);
Map<String,Object> cisMap = arBusi.getTodoPageList(arForm,sessUser,errors);
List AcList = null;// 當頁的記錄
if (null != cisMap) {
AcList = (List) cisMap.get("list");
}
//導出excel的路徑、文件名
String uuid = UUID.create("exp");
String path = request.getSession().getServletContext().getRealPath("/") + ConstValues.EXP_PATH_EXCEL + uuid + ".xls";
acBusi.exprotAcExcel(AcList, path,request);
response.sendRedirect("stdownload.jsp?path=" + path );
}
❸ java如何實現從伺服器下載已經生成好的excel文件
使用 HttpURLConnection 去下載 ,按二進制保存文件 ~~~~~~~~~
❹ java 將頁面內容寫入excel文件中並可以將其下載到本地任意位置
java本身要生成excel文件必然是在後台做的,通過poi庫生成excel文件並製作表格。
無法直接通過網頁保存生成excel。
至於下載到本地任意位置,也是後台生成了excel文件發送到前台(瀏覽器),由用戶選擇要存在哪兒,不能直接存儲(這是web沙箱限制,不允許網頁直接訪問本地硬碟,不然你想想,如果你打開一個網頁,網頁代碼可以任意訪問你的硬碟,你還敢開網頁嗎)。
要繞過沙箱限制必須裝插件,也就是,你必須開發一個com或plugin插件,可以訪問本地硬碟,但這需要用戶手工安裝(比如flash的插件,你之所以能用網頁看flash是因為裝了它的插件,但這是你手工裝的,它不能繞過你直接給你裝,它必須詢問你行不行,你要手工點了OK,才能裝)
❺ java如何將導出的excel下載到客戶端
packagecom.mr;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*利用Servlet導出Excel
*@authorCHUNBIN
*
*/
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("UTF-8");//設置request的編碼方式,防止中文亂碼
StringfileName="導出數據";//設置導出的文件名稱
StringBuffersb=newStringBuffer(request.getParameter("tableInfo"));//將表格信息放入內存
StringcontentType="application/vnd.ms-excel";//定義導出文件的格式的字元串
StringrecommendedName=newString(fileName.getBytes(),"iso_8859_1");//設置文件名稱的編碼格式
response.setContentType(contentType);//設置導出文件格式
response.setHeader("Content-Disposition","attachment;filename="+recommendedName+""");//
response.resetBuffer();
//利用輸出輸入流導出文件
ServletOutputStreamsos=response.getOutputStream();
sos.write(sb.toString().getBytes());
sos.flush();
sos.close();
}
}
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>導出Excel</title>
<scripttype="text/javascript">
functiontest(){
document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;
}
</script>
<style>
body{font-family:宋體;font-size:11pt}
</style>
</head>
<body>
<formaction="<%=request.getContextPath()%>/servlet/ExportExcelServlet"method="post">
<spanid="table">
<tablebgcolor="#EEECF2"bordercolor="#A3B2CC"border="1"cellspacing="0">
<tr><th>學號</th><th>姓名</th><th>科目</th><th>分數</th></tr>
<tr><td>10001</td><td>趙二</td><td>高數</td><td>82</td></tr>
<tr><td>10002</td><td>張三</td><td>高數</td><td>94</td></tr>
<tr><td>10001</td><td>趙二</td><td>線數</td><td>77</td></tr>
<tr><td>10002</td><td>張三</td><td>線數</td><td>61</td></tr>
</table>
</span><br/>
<inputtype="submit"name="Excel"value="導出表格"onclick="test()"/>
<inputtype="hidden"id="tableInfo"name="tableInfo"value=""/>
</form>
</body>
</html>
以上代碼來自網路:http://jtlyuan.iteye.com/blog/1322097
❻ java導出excel
public String downModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/") + "doc/";
String fileName = request.getParameter("fileName") == null ? "" : request.getParameter(
"fileName").trim();
String downLoadPath = ctxPath + fileName;
try {
long fileLength = new File(downLoadPath).length();
/*response.setHeader("Content-disposition", "attachment; filename="
+ new String(fileName.getBytes("utf-8"), "ISO8859-1")); */
String agent= request.getHeader("USER-AGENT");System.out.println(agent);
if (null != agent && -1 != agent.indexOf("MSIE")) {
response.addHeader("Content-Disposition","attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", " ") + "\"");
} else if (null != agent && -1 != agent.indexOf("Firefox")) {
response.addHeader("Content-Disposition","attachment; filename=\"" + new String(fileName.getBytes(), "iso8859-1") + "\"");
}else{
response.setHeader("Content-Disposition","attachment;filename="+new String(java.net.URLEncoder.encode(fileName,"utf-8").getBytes(),"iso8859-1"));
}
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
差不多是這樣,點擊按鈕時候走這個方法, path 跟 name那塊需要根據你自己的情況改下。
❼ java web項目: 一個excel文件以二進制的形式存在資料庫中 如何將它導出並
poi讀取即可。
/**
* 讀取Excel數據內容
* @param InputStream
* @return Map 包含單元格數據內容的Map對象
*/
public Map<Integer, String> readExcelContent(InputStream is) {
Map<Integer, String> content = new HashMap<Integer, String>();
String str = "";
try {
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
while (j < colNum) {
// 每個單元格的數據內容用"-"分割開,以後需要時用String類的replace()方法還原數據
// 也可以將每個單元格的數據設置到一個javabean的屬性中,此時需要新建一個javabean
// str += getStringCellValue(row.getCell((short) j)).trim() +
// "-";
str += getCellFormatValue(row.getCell((short) j)).trim() + " ";
j++;
}
content.put(i, str);
str = "";
}
return content;
}
❽ Java導出execl並下載
struts2 Action的類中代碼
public void createExecl() throws WriteException, IOException{
WritableWorkbook book=null;
@SuppressWarnings("unused")
WritableSheet sheet=null;
try{
String path="C:\\test.xls";
File file=new File(path);
//打開文件
book = Workbook.createWorkbook(file);
// 生成名為「第一頁」的工作表,參數0表示這是第一頁
sheet = book.createSheet( " 第一頁 " , 0 );
// 在Label對象的構造子中指名單元格位置是第一列第一行(0,0)
}catch(Exception e){
System.out.println(e);
}finally{
//寫入數據並關閉文件
book.write();
book.close();
}
try {
String path="C:\\test.xls";
File file=new File(path);
// Excel獲得文件
Workbook wb = Workbook.getWorkbook(file);
// 打開一個文件的副本,並且指定數據寫回到原文件
WritableWorkbook book2 = Workbook.createWorkbook(file, wb);
// 添加一個工作表
//WritableSheet sheet = book.createSheet( " 第二頁 " , 1 );
//WritableSheet sheet = book.getSheet(0);
WritableSheet sheet2=book2.getSheet(0);
// 在Label對象的構造子中指名單元格位置是第一列第一行(0,0)
// 以及單元格內容為test
Label label=null;
Label label2=null;
label=new Label(0,0,"計費Id");
sheet2.addCell(label);
label=new Label(1,0,"主動呼叫號碼");
sheet2.addCell(label);
label=new Label(2,0,"被動呼叫號碼");
sheet2.addCell(label);
label=new Label(3,0,"計費開始時間");
sheet2.addCell(label);
label=new Label(4,0,"計費結束時間");
sheet2.addCell(label);
label=new Label(5,0,"計費單價");
sheet2.addCell(label);
label=new Label(6,0,"計費總金額");
sheet2.addCell(label);
label=new Label(7,0,"扣費號碼");
sheet2.addCell(label);
label=new Label(8,0,"活動名稱");
sheet2.addCell(label);
label=new Label(9,0,"備注");
sheet2.addCell(label);
int j=1;
List<Object> list=baseManager.findByHql("from TalkInformationBean tb left join fetch tb.activeBean order by tb.talkId desc tb.talkId");
Iterator<Object> it=list.iterator();
while(it.hasNext()){
talkInfo=(TalkInformationBean)it.next();
label2 = new Label( 0 , j , talkInfo.getTalkId().toString() );
sheet2.addCell(label2);
label2 = new Label( 1 , j , talkInfo.getInitiMobile().toString() );
sheet2.addCell(label2);
label2 = new Label( 2 , j , talkInfo.getPassMobile().toString() );
sheet2.addCell(label2);
label2 = new Label( 3 , j , talkInfo.getStartTime().toString() );
sheet2.addCell(label2);
label2 = new Label( 4 , j , talkInfo.getEndTime().toString() );
sheet2.addCell(label2);
label2 = new Label( 5 , j , talkInfo.getPrice().toString() );
sheet2.addCell(label2);
label2 = new Label( 6 , j , talkInfo.getTotalMoney().toString() );
sheet2.addCell(label2);
label2 = new Label( 7 , j , talkInfo.getDectMobile().toString() );
sheet2.addCell(label2);
if(talkInfo.getActiveBean()==null){
label2 = new Label( 8 , j , null);
}else{
label2 = new Label( 8 , j , talkInfo.getActiveBean().getActiveName().toString());
}
sheet2.addCell(label2);
label2 = new Label( 9 , j , talkInfo.getRemark().toString() );
sheet2.addCell(label2);
j++;
}
// 將定義好的單元格添加到工作表中
book2.write();
book2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public InputStream getDownloadFile() {
File file = new File("C:\\test.xls");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return fis;
}
/**
* 查詢所有通話記錄
*
* @param
*
* @return
* String success --> 歡迎頁面 fail --> 錯誤頁面
* @throws IOException
* @throws WriteException
* @throws
* HRException
*/
@SuppressWarnings("unchecked")
public String toexport() throws WriteException, IOException{
this.createExecl();
return "success";
}
struts.xml代碼
<action name="toexport" class="talkAction" method="toexport">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="test.xls"</param>
<param name="inputName">downloadFile</param>
</result>
<result name="TALKINFO">/talkInfo/talkInfo.jsp</result>
</action>
JSP頁面代碼
<input class="input_back" type="button" name="Submit0" value="導出數據"onclick="location.href='toexport.action'"/></td>
❾ java : 一個excel文件以二進制的形式存在資料庫中 如何將它導出並下載到本地
從資料庫中得到Blob/Clob,然後得到InputStream,直接給response.getOutputStream() 輸出就可以