当前位置:首页 » 数据仓库 » 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>