當前位置:首頁 » 數據倉庫 » struts2上傳excel到資料庫
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

struts2上傳excel到資料庫

發布時間: 2022-09-10 05:58:40

㈠ 你好 Struts2上傳Excel文件里的內容到資料庫存起來 怎麼弄呢能不能把代碼等等發下謝謝呢

這個得先將文件保存到伺服器中 在去讀取這些數據 在保存到資料庫。你首先得保存文件,struct2
獲取文件比較簡單,讀取excel文件中的數據這個有專門的api,你可以用poi(這個比較穩定) 保存進資料庫你肯定會。你不妨按照我說的分開搜索一下,這個網上很多的。

㈡ struts2,導入excel文件中的內容到資料庫中,如何向action傳遞excel文件絕對路徑

String path_ = ServletActionContext.getRequest().getSession()
.getServletContext().getRealPath("/")+"相對路徑";

㈢ struts2中將excel導入到資料庫myeclipse

/**
*通過filePath參數,找到對應excel文件,讀取表中數據放入List<String[]>集合中
*@paramfilePath
*@return
*/
privateList<String[]>getExcel(StringfilePath){
List<String[]>list=newArrayList<String[]>();
String[]arr=null;
try{
//把一張xls的數據表讀到wb里
//HSSFWorkbookwb=newHSSFWorkbook(newFileInputStream(newFile("F:/test.xls")));
HSSFWorkbookwb=newHSSFWorkbook(newFileInputStream(newFile(filePath)));
//讀取第一頁,這里獲取第一個工作表來進行操作
HSSFSheetsheet=wb.getSheetAt(0);
//循環遍歷表,sheet.getLastRowNum()是獲取一個表最後一條記錄的記錄號
for(intj=1;j<=sheet.getLastRowNum();j++){
//創建一個行對象
HSSFRowrow=sheet.getRow(j);
intl=row.getLastCellNum();
arr=newString[l+1];
//把一行里的每一個欄位遍歷出來
for(inti=0;i<l;i++){
if(i==5||i==6){
arr[i]=String.valueOf((long)row.getCell((short)i).getNumericCellValue());
}else{
//創建一個行里的一個欄位的對象,也就是獲取到的一個單元格中的值
HSSFCellcell=row.getCell((short)i);
arr[i]=cell.getRichStringCellValue().toString();
}
}
list.add(arr);
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnlist;
}

/**
*從getExcel()方法中得到要插入的各行,將其插入到資料庫學生基本信息表中
*一旦出現錯誤,則跳出插入循環體,返回插入的List<StudentBean>集合
*@paramfilePath
*@return
*/
publicList<StudentBean>initStuInfo(StringfilePath){
booleansign=false;
String[]arr=null;
Stringsql="";
StudentBeansb=null;
List<String[]>list=newArrayList<String[]>();
List<StudentBean>insertList=newArrayList<StudentBean>();
filePath=""/*----------Excel文件路徑---------------*/;
list=this.getExcel(filePath);
for(inti=0;i<list.size();i++){
arr=list.get(i);
sb=newStudentBean();
sb.setStuID(arr[0]);
sb.setStuName(arr[1]);
sb.setSex(arr[2]);
sql="insertintodormitory.`stu_info`(stu_id,stu_name,sex,college,major,grade,class_id,birthday,nation,idnumber,addr,status)values("
+"'"+sb.getStuID()+"','"+sb.getStuName()+"','"+sb.getSex()+"')";
sign=conn.getExecuteUpdate(sql);
if(!sign){
break;
}
insertList.add(sb);
}
returninsertList;
}

㈣ 在struts2中,將上傳的excel文件中的內容保存到sql 2005的表中的代碼怎麼寫

讀取excel,把相關的欄位值放到insert into table(欄位1,欄位2,欄位3……) values(讀取的內容對應上即可)

㈤ struts2 從資料庫 導出Excel

public class ExcelHelperPro {
private static final Log log = LogFactory.getLog(ExcelHelper.class);

public static final int FMT_TITLE = 1;
public static final int FMT_KEY = 2;
public static final int FMT_DATA = 3;

private OutputStream outStream;
private HttpServletResponse response;
private String font;
private int fontSize;

private int sheetCounter;//工作表計數器

private WritableWorkbook book = null;

private List partsList;
private List partsTitle;
private List linesList;

WritableCellFormat titleFormat;
WritableCellFormat keyFormat;
WritableCellFormat dataFormat;

public void setFont(String font) {
this.font = font;
}

public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}

private void setResponse(HttpServletResponse response) {
this.response = response;
this.response.setContentType("application/vnd.ms-excel");
try {
this.outStream = response.getOutputStream();
} catch (IOException e) {
log.debug("get outputStream from response error: " + e);
}
}

public ExcelHelperPro(HttpServletResponse response, String fileName) throws Exception {
setResponse(response);//設置輸出流

font = "宋體";
fontSize = 9;
sheetCounter = 0;
partsList = new ArrayList();
partsTitle = new ArrayList();
linesList = new ArrayList();

titleFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont(font), fontSize,
WritableFont.BOLD));
titleFormat.setBackground(Colour.VERY_LIGHT_YELLOW);
titleFormat.setBorder(Border.ALL, BorderLineStyle.MEDIUM);

keyFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont(font), fontSize, WritableFont.BOLD));
keyFormat.setBorder(Border.ALL, BorderLineStyle.THIN);

dataFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont(font), fontSize));

try {
book = Workbook.createWorkbook(outStream);
if (fileName != null) {
this.response.addHeader("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8")
+ "\"");
}
} catch (Exception e) {
log.error("Create Excel Failed: " + e);
e.printStackTrace();
}
}

public void addSheet(List dataList, String sheetName) throws Exception {
WritableSheet sheet = getNewSheet(sheetName);
if (dataList == null || dataList.size() == 0) {
return;
}

// 生成標題
Map firstItem = (Map) dataList.get(0);
Object[] keys = firstItem.keySet().toArray();
for (int j = 0; j < keys.length; j++) {
Label label = new Label(j, 0, (String) keys[j], keyFormat);
sheet.addCell(label);
}

// 生成數據行
for (int j = 0; j < dataList.size(); j++) {
Map item = (Map) dataList.get(j);
for (int k = 0; k < keys.length; k++) {
// 設置數據行位置
int lineNum = j + 1;
Object value = item.get(keys[k]);
Label label = new Label(k, lineNum, value == null ? "" : value.toString(), dataFormat);
sheet.addCell(label);
}
}
}

/**
* 添加數據部分
* @param dataList
* @param title
* @throws Exception
*/
public void addSheetPart(List dataList, String title) throws Exception {
partsList.add(dataList);
partsTitle.add(title);
}

public void addSheetFromPart(String sheetName) throws Exception {
WritableSheet sheet = getNewSheet(sheetName);
if (partsList.size() > 0) {
int lineCounter = 0;//行計數器

List dataList = null;
Label title = null;
Label label = null;

for (int i = 0; i < partsList.size(); i++) {
dataList = (List) partsList.get(i);
if (dataList.size() == 0) {
title = new Label(0, lineCounter, (String) partsTitle.get(i), titleFormat);
sheet.addCell(title);
lineCounter++;
label = new Label(0, lineCounter, "", dataFormat);
sheet.addCell(label);
lineCounter++;
continue;
}

// 獲取標題信息
Map firstItem = (Map) dataList.get(0);
Object[] keys = firstItem.keySet().toArray();

// 寫入Title
title = new Label(0, lineCounter, (String) partsTitle.get(i), titleFormat);
sheet.mergeCells(0, lineCounter, keys.length - 1, lineCounter);
sheet.addCell(title);
lineCounter++;

// 寫入表頭
for (int j = 0; j < keys.length; j++) {
label = new Label(j, lineCounter, (String) keys[j], keyFormat);
sheet.addCell(label);
}
lineCounter++;

// 生成數據行
for (int j = 0; j < dataList.size(); j++) {
Map item = (Map) dataList.get(j);
for (int k = 0; k < keys.length; k++) {
Object value = item.get(keys[k]);
label = new Label(k, lineCounter, value == null ? "" : value.toString(), dataFormat);
sheet.addCell(label);
}
lineCounter++;
}
}
partsList.clear();
partsTitle.clear();
}
}

/**
* 添加數據行
*/
public void addLine(String[] text) {
addLine(text, FMT_DATA, 1);
}

/**
* 添加數據行
*/
public void addLine(String[] text, int format) {
addLine(text, format, 1);
}

/**
* 添加數據行
*/
public void addLine(String[] text, int format, int colspan) {
if (format == FMT_TITLE) {
linesList.add(new LineInfo(text, titleFormat, colspan));
} else if (format == FMT_KEY) {
linesList.add(new LineInfo(text, keyFormat, colspan));
} else {
linesList.add(new LineInfo(text, dataFormat, colspan));
}
}

/**
* 將數據行中寫入Sheet
*/
public void addSheetFromLine(String sheetName) throws Exception {
WritableSheet sheet = getNewSheet(sheetName);
if (linesList.size() > 0) {
LineInfo li = null;
Label label = null;

for (int i = 0; i < linesList.size(); i++) {
li = (LineInfo) linesList.get(i);

for (int j = 0; j < li.text.length; j++) {
label = new Label(j, i, li.text[j] == null ? "" : li.text[j], li.format);
if ((li.colspan > 1) && (li.text.length == 1)) {
sheet.mergeCells(0, i, li.colspan - 1, i);
}
sheet.addCell(label);
}
}
linesList.clear();
}
}

public void writeExcel() throws Exception {
book.write();
book.close();
}

private WritableSheet getNewSheet(String sheetName) {
WritableSheet sheet = book.createSheet(sheetName, sheetCounter++);
formatSheet(sheet);
return sheet;
}

private void formatSheet(WritableSheet sheet) {
SheetSettings ss = sheet.getSettings();
ss.setDefaultColumnWidth(20);
ss.setDefaultRowHeight(300);
}
}

/**
* Sheet行信息
*/
class LineInfo {
protected String[] text;
protected WritableCellFormat format;
protected int colspan;

public LineInfo(String[] text, WritableCellFormat format, int colspan) {
this.text = text;
this.format = format;
this.colspan = colspan;
}
}
有問題我qq160766790

㈥ struts2+extjs上傳excel文件的問題

給你extjs能執行的你研究一下
我覺得你設置 xtype: 'filefield', 能好用
*************************************************************************
*上傳框組件
*
************************************************************************
*/
Ext.define('Mocoolka.web.coreview.container.MKUploadForm', {
extend:'Ext.form.Panel',
frame: true,
autoScroll: true,
initComponent: function () {
var me = this;

me.title = getUIWithID("SystemUI.Buttons.Upload.Description");//'上傳',

me.items = [
{
xtype: 'filefield',
emptyText: getUIWithID("SystemUI.MKUploadForm.SelectFile.Description"),//'選擇一個文件',
name: 'filename',
buttonText: '...',
buttonConfig: {
iconCls: 'upload-icon'
}
},
];

me.buttons = [{
text: getUIWithID("SystemUI.Buttons.Upload.Description"),//'上傳',
handler: function () {
var form = this.up('form').getForm();

var action = this.up('form').mkaction;
var myaction = "import";
if (action.get("Name") == "ImportAttachment")
myaction = "ImportAttachment";
var url = mkruntimer.getDataManager().getUrlPath(myaction, action);

if (form.isValid()) {
form.submit({
url: url,
waitMsg: getUIWithID("SystemUI.Buttons.Uploading.Description"),//'上傳中...',
success: function (fp, o) {

var form1 = form.owner;
form1.mkcallout(form1.mkcalloutpara, action.result.children);
form1.up('window').close();

},
failure: function (form, action) {
mkerrorutil.processAjaxFailure(action.response);

}
});
}
}
}, {
text: getUIWithID("SystemUI.Buttons.Reset.Description"),//'重設',
handler: function () {
this.up('form').getForm().reset();
}
}, {
text: getUIWithID("SystemUI.Buttons.Cancel.Description"),//'取消',
handler: function () {
this.up('window').close();
}
},
{
text: getUIWithID("SystemUI.MKUploadForm.AddFile.Description"),//'增加一個文件',
handler: function () {
this.up('form').addFile();

}
}
]
me.callParent(arguments);

},
addFile: function () {
var me = this;
me.add({
xtype: 'filefield',
emptyText: getUIWithID("SystemUI.MKUploadForm.SelectFile.Description"),//'選擇一個文件',
fieldLabel: getUIWithID(""),// '文件',
name: 'filename',
buttonText: '',
buttonConfig: {
iconCls: 'upload-icon'
}
});

},
//standardSubmit:false,

bodyPadding: '10 10 0',
flex:1,
defaults: {
anchor: '100%',

msgTarget: 'side',
labelWidth: 50
},
region: 'center',

});

㈦ struts2 導入excel到資料庫

這是一個小例子,使用的jexcel插件,你需要下載相應的jar

㈧ jsp+struts2實現excel表格內容的批量導入

jap內嵌java代碼,java代碼讀取內容,通過<%%>用java代碼操作內容,循環,每次循環都為jsp頁面中table添加一行。。。不過,如果信息多了的話,,,效率是個問題

㈨ 怎麼用struts2上傳xls與xlsx文件,並把表格里每行的數據讀到List里

用poi 上傳的時候先判斷下文件的後綴,根據不同的xls或者xlsx去判斷否則不會兼容xlsx的

㈩ 求一份完整的Struts實現將excel導入mysql資料庫功能的代碼

SQL

<insertid="insert"parameterClass="Student">
INSERTINTOstudent(sid,sname,address,phone)
VALUES(#sid#,#sname#,#address#,#phone#)
</insert>

DAO

publicvoidinsert(Students)throwsSQLException{
sqlMapClient.insert("insert",s);
}
service:
publicvoidexcel2db(Stringfile)throwsSQLException,FileNotFoundException,IOException{
Students=newStudent();
HSSFWorkbookworkbook;
workbook=newHSSFWorkbook(newFileInputStream(file));

HSSFSheetsheet=workbook.getSheet("sheet1");
introws=sheet.getPhysicalNumberOfRows();

//行索引從0開始,第一行(索引為0)為標題,不寫入資料庫,從第二行開始獲取數據
for(intr=1;r<rows;r++){

HSSFRowrow=sheet.getRow(r);
if(row!=null){

//intcells=row.getPhysicalNumberOfCells();
HSSFCellidcell=row.getCell(0);//row.getCell((short)0);
Stringsid=idcell.getStringCellValue();
HSSFCellnamecell=row.getCell(1);//row.getCell((short)1);
Stringsname=namecell.getStringCellValue();
HSSFCelladdcell=row.getCell(2);//row.getCell((short)2);
Stringaddress=addcell.getStringCellValue();
HSSFCellphonecell=row.getCell(3);//row.getCell((short)3);
Stringphone=phonecell.getStringCellValue();

System.out.println("ID:"+sid+" 姓名:"+sname+" 地址:"
+address+" 電話:"+phone);

s.setSid(sid);
s.setSname(sname);
s.setAddress(address);
s.setPhone(phone);
.insert(s);
}
}

}

action:
publicStringimportdata()throwsException{
service.excel2db(file);
returnshow();
}

page:
<s:formaction="show!importdata">
<s:filelabel="ExcelFile:"id="file"name="file"></s:file>
<s:submit></s:submit>
</s:form>