当前位置: 首页 > 知识库问答 >
问题:

使用java将可变列excel表导入mysql

田普松
2023-03-14

我使用apache poi将数据从excel读取到mysql表。我用excel表格做了这个,有两个字段。我的代码是这样的,

try
        {
            fis = new FileInputStream(filePath);


        //creating workbook, sheet(from poi jar file)
        HSSFWorkbook workBook = new HSSFWorkbook(fis);
        HSSFSheet sheet = workBook.getSheetAt(0);
        //Iterator for iterating rows in sheet
        Iterator itr = sheet.iterator();
        while(itr.hasNext())
        {

            HSSFRow row = (HSSFRow) itr.next();
            Iterator cell = row.cellIterator();
            List data = new ArrayList();
            while(cell.hasNext())
            {
                HSSFCell value = (HSSFCell) cell.next();                    
                if (value.getCellType() == Cell.CELL_TYPE_NUMERIC) 
                {
                    data.add(value.getNumericCellValue());
                }
                else if (value.getCellType() == Cell.CELL_TYPE_BOOLEAN) 
                {
                    data.add(value.getBooleanCellValue());
                }
                else if (value.getCellType() == Cell.CELL_TYPE_STRING)
                {
                    data.add(value.getStringCellValue());
                }
            }
            sheetData.add(data);

        }
    }
    catch (Exception e) {
        // TODO: handle exception
    }

然后将数据放在arraylist上。ten将其插入数据库。。但是现在我需要系统来获取具有可变克隆数的excel文件。我能做到吗?我只是急需帮助。因此,请帮助我一些想法和可能的一些代码。

先谢谢你,苏吉

共有3个答案

郭均
2023-03-14

我们还可以使用简单而最佳的方法2将Excel表上传到数据库

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./ExcelSample" method="post" id="formdata"
    enctype="multipart/form-data" onsubmit="return excelUpload('Conform')">
<label for="inputSuccess2" class="control-label">
<div id="scn">Select Excel File</div>
</label> <input type="file" name="excel" id="excelfile"
    class="form-control active"> <label class="control-label">&nbsp;</label>
<input type="submit" class="form-control btn btn-orange" id="Upload"
    value="Upload"></form>
</body>
</html>

package com.excel.Sample.ExcelAnn;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.METHOD)
public @interface ExcelColumn {
    boolean ignore() default false;
    String label() default "";
}

package com.excel.Sample.ExcelAnn;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.TYPE)
public @interface ExcelReport {
    String reportName();
}


    package com.excel.Sample.Actions;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.excel.Sample.ExcelAnn.ExcelColumn;
import com.excel.Sample.ExcelAnn.ExcelReport;

public class ExcelAction {
    private HSSFWorkbook workbook = null;
    private String workbookName = "Book1.xls";
    private Map<String, String> fieldLabelMap = new HashMap<String, String>();
    private List<String> orderLabels = new ArrayList<String>();
    private CellStyle columnHeaderCellStyle = null;

    public ExcelAction() {
        initialize();
    }

    private void initialize() {
        setWorkbook(new HSSFWorkbook());
        setColumnHeaderCellStyle(createColumnHeaderCellStyle());
    }

    private CellStyle createColumnHeaderCellStyle() {
        CellStyle cellStyle = getWorkbook().createCellStyle();
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setFillBackgroundColor(new HSSFColor.GREY_25_PERCENT()
                .getIndex());
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        return cellStyle;
    }

    public void closeWorksheet() {
        FileOutputStream fileOut;
        try {
            fileOut = new FileOutputStream(getWorkbookName());
            getWorkbook().write(fileOut);
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HSSFSheet getSheetWithName(String name) {
        HSSFSheet sheet = workbook.getSheet(name);
        return sheet;
    }

    private void initializeForRead(InputStream inp) throws IOException {
        workbook = new HSSFWorkbook(inp);
    }

    private <T> void processAnnotations(T object) {
        Class<?> clazz = object.getClass();
        ExcelReport reportAnnotation = (ExcelReport) clazz
                .getAnnotation(ExcelReport.class);


        for (Method method : clazz.getMethods()) {

            ExcelColumn excelColumn = method.getAnnotation(ExcelColumn.class);
            if ((excelColumn != null) && !excelColumn.ignore()) {
                getFieldLabelMap().put(excelColumn.label(), method.getName());
                getOrderLabels().add(excelColumn.label());
            }
        }
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> readData(String classname, InputStream inp)
            throws Exception {
        Class clazz = Class.forName(classname);
        processAnnotations(clazz.newInstance());
        initializeForRead(inp);
        HSSFSheet sheet = getSheetWithName("Sheet1");
        List<T> result = new ArrayList<T>();
        Map<String, String> mp = new HashMap<String, String>();
        Iterator<Row> rowIterator = sheet.rowIterator();
        int rowCount = 0;
        while (rowIterator.hasNext()) {
            T one = (T) clazz.newInstance();
            try {
                int colCount = 0;
                result.add(one);
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (rowCount == 0) {
                        mp.put(colCount + "", cell.getStringCellValue()
                                .toString().trim());

                    } else {
                        int type = cell.getCellType();
                        String labelName = mp.get(colCount + "");
                        String getter = getFieldLabelMap().get(labelName);
                        String fieldName = getter.substring(3);
                        fieldName = decapitalize(fieldName);
                        Method method = constructMethod(clazz, fieldName);
                        if (type == 1) {
                            String value = cell.getStringCellValue();
                            Object[] values = new Object[1];
                            values[0] = value;
                            method.invoke(one, values);
                        } else if (type == 0) {
                            Double num = cell.getNumericCellValue();
                            Class<?> returnType = getGetterReturnClass(clazz,
                                    fieldName);
                            if (returnType == Integer.class) {
                                method.invoke(one,(Integer) num.intValue());
                            } else if (returnType == Double.class) {
                                method.invoke(one, (Integer) num.intValue());
                            } else if (returnType == Float.class) {
                                method.invoke(one, num.floatValue());
                            } else if (returnType == Date.class) {
                                method.invoke(one, cell.getDateCellValue());
                            }
                        } else if (type == 3) {
                            double num = cell.getNumericCellValue();
                            Object[] values = new Object[1];
                            values[0] = num;
                            method.invoke(one, values);
                        }
                    }
                    colCount++;
                }
            } catch (Exception e) {
                System.out.println(e);
            }
            rowCount++;
        }
        return result;
    }

    private Class<?> getGetterReturnClass(Class<?> clazz, String fieldName) {
        String methodName = "get" + capitalize(fieldName);
        Class<?> returnType = null;
        for (Method method : clazz.getMethods()) {
            if (method.getName().equals(methodName)) {
                returnType = method.getReturnType();
                break;
            }
        }
        return returnType;
    }

    @SuppressWarnings("unchecked")
    private Method constructMethod(Class clazz, String fieldName)
            throws SecurityException, NoSuchMethodException {
        Class<?> fieldClass = getGetterReturnClass(clazz, fieldName);
        return clazz.getMethod("set" + capitalize(fieldName), fieldClass);
    }

    public <T> void writeReportToExcel(List<T> data) throws Exception {
        processAnnotations(data.get(0));
        Sheet sheet = getWorkbook().createSheet(
                data.get(0).getClass().getName());
        int rowCount = 0;
        int columnCount = 0;
        Row row = sheet.createRow(rowCount++);
        for (String labelName : getOrderLabels()) {
            Cell cel = row.createCell(columnCount++);
            cel.setCellValue(labelName);
            cel.setCellStyle(getColumnHeaderCellStyle());
        }
        Class<? extends Object> classz = data.get(0).getClass();
        for (T t : data) {
            row = sheet.createRow(rowCount++);

            columnCount = 0;

            for (String label : getOrderLabels()) {
                String methodName = getFieldLabelMap().get(label);
                Cell cel = row.createCell(columnCount);
                Method method = classz.getMethod(methodName);
                Object value = method.invoke(t, (Object[]) null);
                if (value != null) {
                    if (value instanceof String) {
                        cel.setCellValue((String) value);
                    } else if (value instanceof Long) {
                        cel.setCellValue((Long) value);
                    } else if (value instanceof Integer) {
                        cel.setCellValue((Integer) value);
                    } else if (value instanceof Double) {
                        cel.setCellValue((Double) value);
                    }
                }
                columnCount++;
            }
        }
    }

    public Map<String, String> getFieldLabelMap() {
        return fieldLabelMap;
    }

    public void setFieldLabelMap(Map<String, String> fieldLabelMap) {
        this.fieldLabelMap = fieldLabelMap;
    }

    public List<String> getOrderLabels() {
        return orderLabels;
    }

    public void setOrderLabels(List<String> orderLabels) {
        this.orderLabels = orderLabels;
    }

    public String capitalize(String string) {
        String capital = string.substring(0, 1).toUpperCase();
        return capital + string.substring(1);
    }

    public String decapitalize(String string) {
        String capital = string.substring(0, 1).toLowerCase();
        return capital + string.substring(1);
    }

    public String getWorkbookName() {
        return workbookName;
    }

    public void setWorkbookName(String workbookName) {
        this.workbookName = workbookName;
    }

    void setWorkbook(HSSFWorkbook workbook) {
        this.workbook = workbook;
    }

    Workbook getWorkbook() {
        return workbook;
    }

    public CellStyle getColumnHeaderCellStyle() {
        return columnHeaderCellStyle;
    }

    public void setColumnHeaderCellStyle(CellStyle columnHeaderCellStyle) {
        this.columnHeaderCellStyle = columnHeaderCellStyle;
    }

}


package com.excel.Sample.Model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.excel.Sample.ExcelAnn.ExcelColumn;

@Entity
@Table(name = "directory")
public class Directory {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @Column(name = "Test_Name")
    private String name;
    @Column(name = "Path", nullable = false)
    private String path;
    @Column(name = "Directory", nullable = false)
    private String directory;
    @Column(name = "ContainedFiles", nullable = false)
    private Integer containedFiles;

    @Column(name = "DateFormate", nullable = false)
    private Date dateFormate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ExcelColumn(label = "Test Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ExcelColumn(label = "Path")
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @ExcelColumn(label = "Directory")
    public String getDirectory() {
        return directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    @ExcelColumn(label = "ContainedFiles")
    public Integer getContainedFiles() {
        return containedFiles;
    }

    public void setContainedFiles(Integer containedFiles) {
        this.containedFiles = containedFiles;
    }

    @ExcelColumn(label = "DateFormate")
    public Date getDateFormate() {
        return dateFormate;
    }

    public void setDateFormate(Date dateFormate) {
        this.dateFormate = dateFormate;
    }
}

package com.excel.Sample.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.excel.Sample.Actions.ExcelAction;
import com.excel.Sample.Model.Directory;
import com.excel.util.HibernateUtil;

/**
 * Servlet implementation class ExcelSample
 */
public class ExcelSample extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public static String modelName = "com.excel.Sample.Model.Directory";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExcelSample() {
        super();

        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        try {

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.getMessage();
                }
                FileItem item = (FileItem) items.get(0);
                try {
                    ExcelAction ea = new ExcelAction();
                    List<Directory> e = ea.readData(modelName, item
                            .getInputStream());
                    out.println("<table>");
                    for (int i = 1; i < e.size(); i++) {
                        Directory ex = (Directory) e.get(i);
                        Session session = HibernateUtil.getSessionFactory()
                                .openSession();
                        Transaction transaction = null;

                        try {
                            transaction = session.beginTransaction();
                            session.save(ex);
                            transaction.commit();
                        } catch (HibernateException exp) {
                            transaction.rollback();
                            exp.printStackTrace();
                        } finally {
                            session.close();
                        }
                        String date = new SimpleDateFormat("dd/MM/yyyy")
                                .format(ex.getDateFormate());
                        out.println("<tr><td>" + ex.getContainedFiles()
                                + " </td><td> " + ex.getDirectory()
                                + " </td><td> " + ex.getPath() + " </td><td> "
                                + ex.getName() + "</td><td> " + date
                                + "</td></tr>");
                    }
                    out.println("</table>");
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }

    }

}
  1. Mate的Excel如下

测试名称路径目录包含文件日期格式。settings/home/david/dev/workspace/2009年12月/ExcelAnnotationReport/。设置目录1 2013年5月2日src/home/david/dev/workspace/Dec2009/ExcelAnnotationReport/src目录1 2013年12月3日。classpath1/home/david/dev/workspace/Dec2009/ExcelAnnotationReport/。classpath1文件1 1 2013年4月11日测试/home/david/dev/workspace/2009年12月/ExcelAnnotationReport/test目录1 2013年5月3日测试。xls/home/david/dev/workspace/2009年12月/ExcelAnnotationReport/test。xls文件11 2013年6月6日。project/home/david/dev/workspace/2009年12月/ExcelAnnotationReport/。项目文件1 2013年12月7日bin/home/david/dev/workspace/2009年12月/ExcelAnnotationReport/bin目录1 2013年6月8日

李鹏
2023-03-14

您可以使用excel工作表的第一行存储mysql表的列名,因此您将有一个列索引-列名映射信息。

然后,当insert到mysql表时,可以选择第一行中的列名进行操作。例如

Excel 1

   =========================
   | A      | B      | C
===+========+========+======
1  | name   | gender | age   <-- column name row
---+--------+--------+------
2  | josh   | male   | 28
---+--------+--------+------
3  | linda  | female | 22
----------------------------

SQL 1

INSERT INTO table (name, gender, age) VALUES ('josh', 'male', 28),('linda', 'female', 22)

Excel 2

   ==================
   | A      | B 
===+========+========
1  | name   | country <-- column name row
---+--------+--------
2  | 张三   | China
---+--------+--------
3  | emily  | USA
---------------------

SQL2

INSERT INTO table (name, country) VALUES ('张三', 'China'),('emily', 'USA')
韩彬
2023-03-14

迭代单行时

if (value.getCellType() == Cell.CELL_TYPE_NUMERIC){
                     data.add(value.getNumericCellValue());                 
}

您可以添加一个新的if块,用于检查

if(value.getCellType() == Cell.CELL_TYPE_BLANK){
break;
}

在这里,我假设您列中的所有数据都是同时的(1 2 3 4空白),而不是这样(1空白2 3 4 5)。因此,当您得到空白类型时,迭代器将转移到下一行。

希望这有帮助。

 类似资料:
  • 我正在编写一个程序,它将数据写入excel表格的表格格式。我的代码提供了我想要的所有细节。 但是为了得到表格格式,我必须在excel sheet中遵循以下步骤 我想让我的代码自动生成我想要的格式,而不需要我在excel表中执行上面显示的步骤。有人能帮我吗?提前道谢。下面显示的是我的代码。 `

  • 问题内容: 我有一个xlsx格式的下表,我想将其导入到我的sql数据库中: 该表非常复杂,我只需要‘1)HEADING’之后的记录 我一直在寻找要导入sql的php库,但它们似乎仅用于简单的excel文件。 问题答案: 您有两种方法可以实现: 第一种方法: 1)将其导出为某种文本格式。最简单的可能是制表符分隔的版本,但是CSV也可以使用。 2)使用负载数据功能。参见http://dev.mysql

  • 问题内容: 我正在尝试使用VBA将数据表从excel导入SQL Server 2012。 最好在UDF的帮助下。 excel表看起来像这样。 (我将数字放在单元格中以指定其位置。例如11 =第1行,第1列) 数据库表看起来像这样。 (这不包括“主键”列,该列可以是id和year的组合,也可以是a ) 我知道如何导入特定的列,例如,我可以运行以下代码: 这对于单个列非常有用,但是我将如何使其适用于整

  • 通过下面的函数,您可以通过PHP将数据从Excel电子表格导入数据库。 表包含以下字段: 但我需要以下列:以导入另一个发票表,该表将包含以下字段: 其中client_id将接收客户端id。 我使用以下方法导入: 控制器 模型

  • 问题内容: 我有一个大约有2000条记录的CSV文件。 每个记录都有一个字符串和一个类别: 我需要将此文件读入如下列表: 如何使用Python将CSV导入到我需要的列表中? 问题答案: 使用csv模块: 输出: 如果你需要元组: 输出: 旧的Python 2答案,也使用csv模块:

  • 我是新的Python和工作在我的第一个项目。我试图让我的代码从一个电子表格中复制数据列,并将其附加到当前存在于主表中的数据中。我能够捕获每个工作表中的数据,并创建一个新的主列表,该列表结合了两个数据集,但我很难将其写入文件。当我测试打印组合列表时,它们看起来是正确的,但是当我添加代码将列表写入文件时,它会挂起。 你能提供的任何帮助都会非常有用! 下面是我的代码。这是我得到的错误 Traceback