乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > 你好! 请教你个问题 <em>java</em> <em>web</em>

你好! 请教你个问题 <em>java</em> <em>web</em>

作者:乔山办公网日期:

返回目录:excel表格制作


有两种方法一个是用POI,另一种是JXL都是别人的包,自己操作到处excel
自己在前端写一个弹出窗口选择路径之后传到代码里操作
并不能像javaswing那样方便的使用导入导出功能web需要自己实现

主要用poi.jar 包。包含两个jar就可以了:poi-3.16.jar、poi-ooxml-3.16.jar

主要方法分三步:

/**
* filePath 文件路径
* unCaseRow  要排除的行数(从上往下)
* unCaseLine  要排除的列数(从左往右)
*/
public List<String[]> readExcel(String filePath, int unCaseRow, int unCaseLine) throws Exception {
   Sheet sheet = null;
    FileInputStream inStream = null;
e68a84e8a2ad7a686964616f363try {
inStream = new FileInputStream(new File(filePath));
Workbook workBook = WorkbookFactory.create(inStream);

sheet = workBook.getSheetAt(0);
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
} finally {
try {
if (inStream != null) {
inStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

List<String[]> list = init(sheet, unCaseRow, unCaseLine);// 需要排除行数

return list;
}

// 初始化表格中的每一行,并得到每一个单元格的值
private List<String[]> init(Sheet sheet, int unCaseRow, int unCaseLine) {
int rowNum = sheet.getLastRowNum() + 1; // 从零开始
List<String[]> result = new ArrayList<String[]>();
String[] rowArr = null;

Row row = null;
Cell cell = null;
int rowLength = 0;
int rowIndex = 0;
String rowStr = null;
for (int i = unCaseRow; i < rowNum; i++) {
row = sheet.getRow(i);
// 每有新的一行,创建一个新的LinkedList对象
rowLength = row.getLastCellNum();
rowIndex = 0;
rowArr = new String[LINECOUNT];
for (int j = unCaseLine; j < rowLength; j++) {
cell = row.getCell(j);
// 获取单元格的值
rowStr = getCellValue(cell);
// 将得到的值放入链表中
rowArr[rowIndex++] = rowStr;
}

result.add(rowArr);
}

return result;
}

// 获取单元格的值
@SuppressWarnings("deprecation")
private String getCellValue(Cell cell) {
String cellValue = "";
DataFormatter formatter = new DataFormatter();
if (cell != null) {
// 判断单元格数据的类型,不同类型调用不同的方法
switch (cell.getCellType()) {
// 数值类型
case Cell.CELL_TYPE_NUMERIC:
// 进一步判断 ,单元格格式是日期格式
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = formatter.formatCellValue(cell);
} else {
// 数值
double value = cell.getNumericCellValue();
int intValue = (int) value;
cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
}
break;
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
// 判断单元格是公式格式,需要做一种特殊处理来得到相应的值
case Cell.CELL_TYPE_FORMULA: {
try {
cellValue = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getRichStringCellValue());
}

}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR:
cellValue = "";
break;
default:
cellValue = cell.toString().trim();
break;
}
}
return cellValue.trim();
}

解析成对象以后,不论是插入数据库,还是jsp,都是一样的。

插入数据库:hibernate、mybatis

在jsp显示:对象封装进list,在页面显示list。


1. 要正确的将Web客户端的Excel文件导入到服务器的数据库中,需要将客户端的Excel文件上传到服务器上。可以使用FileUpload控件完成。
  2. Excel文件上传到服务器指定的目录中,这里假设是该站点的upfiles目录中。
  3. 使用SQL语句从upfiles目录中的上传Excel文件中读取数据显示或写入数据库。
  相关代码如下:
  1. 前台文件:
  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="StudentInforInport.aspx.cs" Inherits="StudentInforInport" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http:///1999/xhtml" >
  <head runat="server">
  <link rel="stylesheet" type="text/css" href="css/style.css"/>
  <title>从Excel表中导入学生数据</title>
  </head>
  <body>
  <form id="form1" runat="server">
  <div>
  <table style="width: 96%; border-collapse: separate; text-align: center">
  <tr>
  <td colspan="3">
  从Excel中导入</td>
  </tr>
  <tr>
  <td colspan="3" style="text-align: left; height: 9px;">
  </td>
  </tr>
  <tr>
  <td align="center" style="width: 20%;">
  请选择Excel文件路径</td>
  <td align="center" style="width: 483px; height: 18px; text-align: left">
  <asp:FileUpload ID="FileUpload1" runat="server" Width="555px" /></td>
  <td align="center" style="width: 10%">
  <asp:Button ID="Btn_Inport" runat="server" Text="导 入" OnClick="Btn_Inport_Click" /></td>
  </tr>
  <tr>
  <td align="center">
  请选择表名</td>
  <td align="center" style="width: 483px; height: 18px; text-align: left">
  <asp:DropDownList ID="DDList_Sheet" runat="server"></asp:DropDownList></td>
  <td align="center">
  </td>
  </tr>
  <tr>
  <td colspan="3">
  <asp:GridView ID="GV_Excel" runat="server" Height="133px" Width="100%">
  </asp:GridView>
  </td>
  </tr>
  <tr>
  <td style="height: 18px">
  </td>
  <td style="width: 483px; height: 18px;">
  </td>
  <td style="width: 243px; height: 18px;">
  </td>
  </tr>
  </table>
  </div>
  </form>
  </body>
  </html>
  2. 后台代码:
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  using System.Data.OleDb;
  using System.Data.SqlClient;
  public partial class StudentInforInport : System.Web.UI.Page
  {
  string strConn = System.Configuration.ConfigurationManager.AppSettings["strconn"].ToString().Trim(); //链接SQL数据库
  protected void Page_Load(object sender, EventArgs e)
  {
  }
  /// <summary>
  /// 查询EXCEL电子表格添加到DATASET
  /// </summary>
  /// <param name="filenameurl">服务器路径</param>
  /// <param name="table">表名</param>
  /// <param name="SheetName">Sheet表名</param>
  /// <returns>读取的DataSet </returns>
  public DataSet ExecleDs(string filenameurl, string table, string SheetName)
  {
  string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0'";
  OleDbConnection conn = new OleDbConnection(strConn);
  conn.Open();
  DataSet ds = new DataSet();
  OleDbDataAdapter odda = new OleDbDataAdapter("select * from [" + SheetName + "]", conn);
  odda.Fill(ds, table);
  return ds;
  }
  protected void Btn_Inport_Click(object sender, EventArgs e)
  {
  if (FileUpload1.HasFile == false) //HasFile用来检查FileUpload是否有指定文件
  {
  Response.Write("<script>alert('请您选择Excel文件')</script> ");
  return; //当无文件时,返回
  }
  string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
  if (IsXls != ".xls")
  {
  Response.Write("<script>alert('只可以选择Excel文件')</script>");
  return; //当选择的不是Excel文件时,返回
  }
  string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName; // 获取Execle文件名 DateTime日期函数
  string savePath = Server.MapPath(("~\\upfiles\\") + filename); //Server.MapPath 获得虚拟服务器相对路径
  FileUpload1.SaveAs(savePath); //SaveAs 将上传的636f7079e799bee5baa6e997aee7ad94337文件内容保存在服务器上
  OperExcel Excel = new OperExcel();
  ArrayList AL_ExcelSheet = new ArrayList();
  AL_ExcelSheet = Excel.ExcelSheetName(savePath);
  DDList_Sheet.Items.Clear();
  for (int i = 0; i < AL_ExcelSheet.Count; i++)
  {
  DDList_Sheet.Items.Add( AL_ExcelSheet[i].ToString() );
  }
  SqlConnection cn = new SqlConnection(strConn);
  cn.Open();
  DataSet ds = ExecleDs(savePath, filename, DDList_Sheet.Items[0].ToString()); //调用自定义方法得到数据
  DataTable dt = ds.Tables[0];
  if (dt.Rows.Count == 0)
  {
  Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
  }
  else
  {
  // 数据
  GV_Excel.DataSource = dt;
  GV_Excel.DataBind();
  Response.Write("<script>alert('Excle表导入成功!');location='default.aspx'</script>");
  }
  cn.Close();
  }
  }
  注意:当导入的Excel文件中的内容很大时,将发生莫名的错误。因此导入的文件不能太大,一般少于5MB.

1. 要正确的将Web客户端的Excel文件导入到服务器的数据库中,需要将客户端的Excel文件上传到服务器上。可以使用FileUpload控件完成。
2. Excel文件上传到服务器指定的目录中,这里假设是该站点的upfiles目录中。
3. 使用SQL语句从upfiles目录中的上传Excel文件中读取数据显示或写入数据库。

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网