将Excel表导入MySQL

(1)首先Eclipse要与MySQL使用JDBC进行连接
package com.softeem.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBConnection {

	/*声明链接数据库的基本参数*/
	private static  String DRIVER;
	private static  String URL;
	private static  String USER;
	private static  String PASSWORD; 
	
	//在静态块中加载驱动,防止反复加载
	static{
		try {
			//获取属性对象
			Properties props = System.getProperties();
			//加载指定属性文件,根据属性名获取属性值
			props.load(new FileInputStream("src/jdbc.properties"));
			DRIVER = props.getProperty("driver");
			URL = props.getProperty("url");
			USER = props.getProperty("user");
			PASSWORD = props.getProperty("password");
			
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//封装获取链接的方法
	public static Connection getConn()
	{
		try {
			return DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}

(2)创建MySQL数据库及其表


(3)首先在Eclispe创建一个WorkBook对象,读取Excel文件 

public class ExcelToDB {

	public List
     
     
      
       ReadgoodExcel(File file){
		List
      
      
       
        list = new ArrayList<>();
		goods gs = null;
		Workbook wb = null;
		
		try {
			//创建一个工作簿
			 wb = Workbook.getWorkbook(file);
			 //获取所有表单对象
			 Sheet[] sheets = wb.getSheets();
			 //获取指定索引的表单
			 Sheet sheet = wb.getSheet("Sheet1");
			//获取总行数
			int rows = sheet.getRows();
			for (int i = 1; i < rows; i++) {
				gs = new goods();
				String s1 = sheet.getCell(0, i).getContents();	//编号
				String s2 = sheet.getCell(1, i).getContents();	//商品名
				String s3 = sheet.getCell(2, i).getContents();	//单价
				String s4 = sheet.getCell(3, i).getContents();	//折扣率
				String s5 = sheet.getCell(4, i).getContents();	//时间
				String s6 = sheet.getCell(5, i).getContents();	//库存
				String s7 = sheet.getCell(6, i).getContents();	//类别编号
				
				gs.setGoodsname(s2);
				gs.setId(TypeTools.getInt(s1));
				gs.setPrice(TypeTools.getBigDecimal(s3));
				gs.setOffset(TypeTools.getDouble(s4));
//				long y = TypeTools.getDate(s5).getTime();
//				Date d  =  new Date(y);
//				
				gs.setTime(TypeTools.getDate(s5));
				gs.setCounts(TypeTools.getInt(s6));
				gs.setCid(TypeTools.getInt(s7));
				list.add(gs);
			}
			
		} catch (BiffException | IOException e) {
			e.printStackTrace();
		}
		finally{
			if(wb != null) wb.close();
		}
		return list;
	}
      
      
     
     

然后将WorkBook对象逐一存储到MySQL表中
public void insertgoods(List
       
       
        
         list){
		Connection conn = DBConnection.getConn();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement("insert into goods(id,goodsname,price,offset,time,counts,cid) values(?,?,?,?,?,?,?)");
		    for ( goods g :list ) {
				ps.setInt(1,g.getId());
				ps.setString(2, g.getGoodsname());
				ps.setBigDecimal(3, g.getPrice());
				ps.setDouble(4, g.getOffset());
				ps.setObject(5,g.getTime());
				ps.setInt(6, g.getCounts());
				ps.setInt(7, g.getCid());
				ps.executeUpdate();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
		 try {
			if(ps != null) ps.close();
			if (conn != null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		}
	}
       
       




最后运行即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用WinForm技术将Excel导入MySQL数据库的步骤: 1. 创建WinForm应用程序,并添加必要的组件和引用。 2. 创建一个按钮控件,用于触发导入操作。 3. 在按钮的Click事件中编写代码,实现将Excel读取为数据,然后将数据中的数据插入到MySQL数据库中。 4. 使用Microsoft.Office.Interop.Excel库读取Excel。首先需要在项目中添加对该库的引用。然后在Click事件中使用以下代码读取Excel: ``` using Excel = Microsoft.Office.Interop.Excel; Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(filePath); Excel._Worksheet worksheet = workbook.Sheets[1]; Excel.Range range = worksheet.UsedRange; ``` 其中,`filePath`是Excel的文件路径。 5. 将读取到的数据转换为数据,可以使用以下代码: ``` DataTable dt = new DataTable(); for (int i = 1; i <= range.Columns.Count; i++) { dt.Columns.Add(range.Cells[1, i].Value2.ToString()); } for (int i = 2; i <= range.Rows.Count; i++) { DataRow dr = dt.NewRow(); for (int j = 1; j <= range.Columns.Count; j++) { dr[j - 1] = range.Cells[i, j].Value2; } dt.Rows.Add(dr); } ``` 6. 使用MySql.Data.MySqlClient库连接到MySQL数据库,并将数据中的数据插入到MySQL数据库中。首先需要在项目中添加对该库的引用。然后在Click事件中使用以下代码连接到MySQL数据库: ``` string connectionString = "server=localhost;port=3306;database=mydatabase;user=root;password=mypassword"; MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); ``` 其中,`mydatabase`是MySQL数据库的名称,`root`和`mypassword`是数据库的用户名和密码。 7. 将数据中的数据插入到MySQL数据库中,可以使用以下代码: ``` foreach (DataRow row in dt.Rows) { MySqlCommand command = new MySqlCommand("INSERT INTO mytable (column1, column2, column3) VALUES (?value1, ?value2, ?value3)", connection); command.Parameters.AddWithValue("?value1", row["column1"]); command.Parameters.AddWithValue("?value2", row["column2"]); command.Parameters.AddWithValue("?value3", row["column3"]); command.ExecuteNonQuery(); } ``` 其中,`mytable`是MySQL数据库中的名,`column1`、`column2`和`column3`是中的列名,需要根据实际情况进行修改。 8. 最后,在Click事件中关闭连接并释放资源: ``` connection.Close(); excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); ``` 以上是使用WinForm技术将Excel导入MySQL数据库的步骤。需要注意的是,在读取Excel时,Excel的格式必须与代码中的格式一致,否则可能会导致数据读取错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值