引言
当选择1时,将所有的销售数据导出到 “商品导出.xls” 文件中,导出的时候,还可以为xls文件设置常用的格式,如增加边框、为标题设置背景色,字体、加粗等,成功后显示“成功导出*条销售数据到excel文件中”,返回子菜单。
当选择2时,将所有的销售数据导出到 “商品导出.txt” 文件中,文件的第一行为标题,成功后显示“成功导出*条销售数据到文本文件中”,返回子菜单。
选择3时,返回到主菜单。
功能实现
这次我们还是主讲主函数功能实现,当然在开始代码之前,我们要把相关依赖包加入到项目中,具体步骤详见:Java超市收银系统(八、数据导入)-CSDN博客。
main
方法是程序的入口,包含一个无限循环,用于接收用户输入并执行相应的操作。程序显示一个菜单,提供以下选项:
- 选项 1:导出商品信息到 Excel 文件 (
outputExcel
)- 选项 2:导出商品信息到文本文件 (
outputTxt
)- 选项 3:返回主菜单(退出当前循环)
- default:处理无效输入
outputExcel
方法用于将商品信息导出到 Excel 文件中。文件路径和工作簿创建
- 使用
LocalDate.now()
获取当前日期,并将其格式化为yyyymmdd
格式。- 指定保存 Excel 文件的路径,并创建一个新的可写工作簿 (
WritableWorkbook
)。
创建工作表和设置样式
- 创建一个新的工作表,命名为 "Products"。
- 定义并设置标题行的样式,包括背景颜色、字体、边框等。
写入标题行
- 定义 Excel 文件的标题行,并将其写入工作表的第一行。
查询商品数据并写入工作表
- 从数据库中查询商品数据,利用
ProductDAO.query()
方法获取Product
对象的列表。- 将商品信息逐行写入工作表。
- 将工作簿写入文件,并在最后关闭工作簿。
outputTxt
方法用于将商品信息导出到文本文件中。文件路径和写入器创建
- 指定保存文本文件的目录和文件名。
- 如果目录不存在,则创建该目录。
- 创建
FileWriter
对象用于写入数据。
写入标题行和商品数据
- 写入文本文件的标题行。
- 从数据库中查询商品数据,并逐行写入文件。
- 在完成数据写入后关闭
FileWriter
对象。
总结:
- 该程序的主要功能是从数据库中获取商品信息,并根据用户的选择导出到 Excel 或文本文件中。
- 它使用了
jxl
库来处理 Excel 文件,并使用FileWriter
来处理文本文件。 - 通过捕获并处理异常,程序能够处理文件操作中的潜在错误。
结果展示
数据导出前(路径):
导出后 excel + txt :
完整代码
ui—Driver
package ui;
import dao.ProductDAO;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import vo.Product;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("===****超市商品管理维护====");
System.out.println("1、导出商品信息至excel");
System.out.println("2、导出商品信息至文本文件");
System.out.println("3、返回主菜单");
System.out.println("请选择(1-3):");
int choice = scanner.nextInt();
switch (choice) {
case 1:
outputExcel();
break;
case 2:
outputTxt();
break;
case 3:
System.out.println("返回主菜单");
break;
default:
System.out.println("错误");
}
}
}
private static void outputExcel() {
// 以 yyyymmdd 格式获取当前日期
String currentDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
// 指定附加当前日期的文件路径
String filePath = "D:/1111111111111111111111111/数据导出/商品导出" + ".xls";
// 创建新的可写工作簿
WritableWorkbook workbook = null;
try {
workbook = Workbook.createWorkbook(new File(filePath));
} catch (IOException e) {
throw new RuntimeException(e);
}
// 创建新的可写工作表
WritableSheet sheet = workbook.createSheet("Products", 0);
// 定义单元格格式
WritableCellFormat headerFormat = new WritableCellFormat();
try {
// 设置标题的背景颜色
headerFormat.setBackground(Colour.GREY_25_PERCENT);
// 设置标题的字体样式和粗体
headerFormat.setFont(new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.WHITE));
// 设置标题的边框
headerFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
} catch (WriteException e) {
throw new RuntimeException(e);
}
// 写入标题行
String[] headers = {"商品条码", "商品名称", "单价", "供应商"};
for (int i = 0; i < headers.length; i++) {
Label headerLabel = new Label(i, 0, headers[i], headerFormat);
try {
sheet.addCell(headerLabel);
} catch (WriteException e) {
throw new RuntimeException(e);
}
}
// 从数据库中查询销售数据
List<Product> productList = ProductDAO.query(new Product());
// 定义数据行的单元格格式
WritableCellFormat dataFormat = new WritableCellFormat();
try {
// 设置数据行的边框
dataFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
} catch (WriteException e) {
throw new RuntimeException(e);
}
// 将销售数据写入工作表
int row = 1;
for (Product product : productList) {
try {
sheet.addCell(new Label(0, row, product.getBarCode(), dataFormat));
sheet.addCell(new Label(1, row, product.getProductName(), dataFormat));
sheet.addCell(new jxl.write.Number(2, row, product.getPrice(), dataFormat));
sheet.addCell(new Label(3, row, product.getSupply(), dataFormat));
} catch (WriteException e) {
throw new RuntimeException(e);
}
row++;
}
// 将工作簿写入文件
try {
workbook.write();
System.out.println("成功导出" + productList.size() + "条商品数据到excel种");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException | WriteException e) {
throw new RuntimeException(e);
}
}
}
}
// 导出到文本文件
private static void outputTxt() {
FileWriter writer = null;
try {
// 指定文件保存的目录
String directoryPath = "D:/1111111111111111111111111/数据导出/";
// 创建目录
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs(); // 如果目录不存在,则创建
}
// 指定文件名
String fileName = directoryPath + "商品导出" + ".txt";
// 创建 FileWriter 对象
writer = new FileWriter(fileName);
// 写入标题行
writer.write("商品条码\t商品名称\t单价\t供应商\n");
// 查询销售数据并写入文件
List<Product> productList = ProductDAO.query(new Product());
for (Product product : productList) {
writer.write(product.getBarCode() + "\t" + product.getProductName() + "\t" + product.getPrice() + "\t" + product.getSupply() +"\n");
}
// 输出导出成功信息
System.out.println("成功导出" + productList.size() + "条商品数据到txt中");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
vo—Product
package vo;
public class Product {
private String barCode;
private String productName;
private float price;
private String supply;
public Product() {
}
public Product(String barCode, String productName, float price, String supply) {
this.barCode = barCode;
this.productName = productName;
this.price = price;
this.supply = supply;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getSupply() {
return supply;
}
public void setSupply(String supply) {
this.supply = supply;
}
}
dao—ProductDAO
package dao;
import util.DBUtil;
import vo.Product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ProductDAO {
public static List<Product> query(Product product) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<Product> productList = new ArrayList<>();
try {
con = DBUtil.getConnection();
StringBuilder sql = new StringBuilder("SELECT * FROM t_shangping WHERE 1 = 1");
if (product.getBarCode() != null) {
sql.append(" AND tiaoma = ?");
}
if (product.getProductName() != null) {
sql.append(" AND mingcheng = ?");
}
if (product.getPrice()!=0) {
sql.append(" AND danjia = ?");
}
if (product.getSupply()!=null) {
sql.append(" AND gongyingshang = ?");
}
pst = con.prepareStatement(sql.toString());
int paramIndex = 1;
if (product.getBarCode() != null) {
pst.setString(paramIndex++, product.getBarCode());
}
if (product.getProductName() != null) {
pst.setString(paramIndex++, product.getProductName());
}
if (product.getPrice() != 0) {
pst.setFloat(paramIndex++, product.getPrice());
}
if (product.getSupply() != null) {
pst.setString(paramIndex++, product.getSupply());
}
rs = pst.executeQuery();
while (rs.next()) {
Product p = new Product();
p.setBarCode(rs.getString("tiaoma"));
p.setProductName(rs.getString("mingcheng"));
p.setPrice(rs.getFloat("danjia"));
p.setSupply(rs.getString("gongyingshang"));
productList.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(con, pst);
}
return productList;
}
}
util—DBUtil
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBUtil {
//驱动加载,只需执行一次
static{
String driveName = "com.mysql.cj.jdbc.Driver";
try {
Class.forName(driveName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//获取链接
public static Connection getConnection(){
String url = "jdbc:mysql://localhost:3306/sale?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
Connection con = null;
try {
con = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return con;
}
//关闭资源
public static void close(Connection con, PreparedStatement pst){
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(pst!=null) {
try {
pst.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
mysql
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 80032
Source Host : localhost:3306
Source Database : xiaoshou
Target Server Type : MYSQL
Target Server Version : 80032
File Encoding : 65001
Date: 2023-05-11 10:27:07
*/
SET FOREIGN_KEY_CHECKS=0;
use sale;
-- ----------------------------
-- Table structure for t_shangping
-- ----------------------------
DROP TABLE IF EXISTS `t_shangping`;
CREATE TABLE `t_shangping` (
`tiaoma` varchar(255) NOT NULL,
`mingcheng` varchar(255) DEFAULT NULL,
`danjia` decimal(10,2) DEFAULT NULL,
`gongyingshang` varchar(255) DEFAULT NULL,
PRIMARY KEY (`tiaoma`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
select * from t_shangping;
-- ----------------------------
-- Records of t_shangping
-- ----------------------------
INSERT INTO `t_shangping` VALUES ('100001', '手机', '4500.00', '华为');
INSERT INTO `t_shangping` VALUES ('100002', '鼠标', '61.00', '华为');
INSERT INTO `t_shangping` VALUES ('100003', '矿泉水', '2.50', '农夫山泉');
INSERT INTO `t_shangping` VALUES ('100004', '香烟', '20.00', '武汉卷烟厂');
INSERT INTO `t_shangping` VALUES ('100005', '牙膏', '4.50', '中华牙膏厂');
INSERT INTO `t_shangping` VALUES ('200001', '电脑', '4300.00', 'dell');
INSERT INTO `t_shangping` VALUES ('200002', '小明同学', '5.50', '武汉饮料集团');
-- ----------------------------
-- Table structure for t_shouyinmingxi
-- ----------------------------
DROP TABLE IF EXISTS `t_shouyinmingxi`;
CREATE TABLE `t_shouyinmingxi` (
`liushuihao` varchar(255) NOT NULL,
`tiaoma` varchar(255) DEFAULT NULL,
`mingcheng` varchar(255) DEFAULT NULL,
`danjia` decimal(10,0) DEFAULT NULL,
`shuliang` int DEFAULT NULL,
`shouyinyuan` varchar(255) DEFAULT NULL,
`xiaoshoushijian` datetime DEFAULT NULL,
PRIMARY KEY (`liushuihao`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
select * from t_shouyinmingxi;
-- ----------------------------
-- Records of t_shouyinmingxi
-- ----------------------------
-- ----------------------------
-- Table structure for t_yonghu
-- ----------------------------
DROP TABLE IF EXISTS `t_yonghu`;
CREATE TABLE `t_yonghu` (
`yonghuming` varchar(255) NOT NULL,
`mima` varchar(255) DEFAULT NULL,
`xingming` varchar(255) DEFAULT NULL,
`juese` varchar(255) DEFAULT NULL,
PRIMARY KEY (`yonghuming`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
select * from t_yonghu;
-- ----------------------------
-- Records of t_yonghu
-- ----------------------------
INSERT INTO `t_yonghu` VALUES ('mk', 'mk123', '明空', '管理员');
INSERT INTO `t_yonghu` VALUES ('jx', 'jx123', '瑾熙', '收银员');
相关其他功能实现请参考前面的博客
Java超市收银系统(一、用户登录)_java商超收银系统-CSDN博客