网页上传Excel文件

前端代码:

<form action="http://你的设置的名字.free.idcfengye.com/weixin/addExcel"
		method="post" enctype="multipart/form-data" name="fileForm">
		<input type="text" id="filename" style="display: none" /> 
		<input type="text" id="file_err" style="display: none" />
		文件代号:<input type = "text" name = "gid" id = "gid" value = "" /><br/>
		<input type="hidden" id ="ma" name = "ma">
		Excel文件(.xls或.xlsx)<input type="file" id="file" name="myfile"  onchange="" style="display: block"  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
		<button type = "submit" class ="but" " >提交</button>
		</form>

后端代码:
addExcel:(这里我是读取Excel然后存入数据库)

protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		System.out.println("post");
		// 请求是否为multipar请求
		if (!ServletFileUpload.isMultipartContent(request)) {
			throw new RuntimeException("当前请求不支持文件上传");
		} else {
			int ma = 0;
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				List<FileItem> items = upload.parseRequest(request);
				String groupid = null;
				int count = 0;
				for (FileItem item : items) {
					if (item.isFormField()) {// 普通表单项
						String fieldName = item.getFieldName();
						String fieldValue = item.getString();
						if(count == 0) {
							groupid = fieldValue;
						}
						if(count == 1) {
							ma = Integer.valueOf(fieldValue);
						}
						System.out.println(fieldName+"="+fieldValue);
						count++;
					} else {
						String fileName = item.getName();// 文件名
						System.out.println(fileName);
						String str = fileName;
						String[] strs = str.split("\\.");
						for (int i = 0; i < strs.length; i++) {
							System.out.println(strs[i]);
						}

						InputStream is = item.getInputStream();
						String path = this.getServletContext().getRealPath("/Excel");
						System.out.println("path"+path);
						File descFile = new File(path,fileName);
						OutputStream os = new FileOutputStream(descFile);
						int len = -1;
						byte[] buf = new byte[1024];
						while ((len = is.read(buf)) != -1) {
							os.write(buf, 0, len);
//							System.out.println("执行循环");
						}
						readExcel re = new readExcel();
						path = path + "\\" + fileName;
						File file1 = new File(path,fileName);
						List<Student> list = null;
						if(strs[1].equals("xls")) {
							list = re.readXls(path);
						}else if(strs[1].equals("xlsx")) {
							list = re.readXlsx(path);
						}
						addHuaMingCe addHua = new addHuaMingCe();
						
						System.out.println("groupid" + "=" + groupid);
						for (Student stu : list) {
							System.out.println("Sevlet" + stu.getStuNum());
							System.out.println(stu.getName());
							System.out.println(stu.getCla());
							addHua.addHuaMing(groupid, stu.getStuNum(), stu.getName(), stu.getCla());
						}
						System.out.println("存储完成");
						os.close();
						is.close();
						if(ma != 0) {
						    System.out.println("ma"+ma);
						    response.sendRedirect("http://.free.idcfengye.com/weixin/setSuccess.html?qiandaoma="+ma);
						}else {
							response.sendRedirect("http://.free.idcfengye.com/weixin/setFail.html");
						}
					}

				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public String getDay(){

readExcel:
上面部分是读取.xls文件,下面部分是读取.xlsx文件。

public class readExcel {//
	public List<Student> readXls(String path) {
		List<Student> list = new ArrayList<>();
		InputStream inp;
		try {
			inp = new FileInputStream(path);
			HSSFWorkbook workbook = new HSSFWorkbook(inp);
			int size = workbook.getNumberOfSheets();
			System.out.println("工作表数:" + size);
			HSSFSheet sheet;
			for (int i = 0; i < size; i++) {
				sheet = workbook.getSheetAt(i);
				System.out.println("读取当前工作表名" + sheet.getSheetName());
				int rowNumber = sheet.getPhysicalNumberOfRows();
				System.out.println("有效行数:" + rowNumber);
				if (rowNumber == 0) {
					continue;
				} else {
					for (int rowIndex = 0; rowIndex < rowNumber; rowIndex++) {
						System.out.println("正在读取第" + (rowIndex + 1) + "行");
						if (rowIndex == 0) {
							continue;
						}
						HSSFRow row = sheet.getRow(rowIndex);
						Student stu = new Student();
						for (int cellIndex = 0; cellIndex < 3; cellIndex++) {
							HSSFCell cell = row.getCell(cellIndex);
							if(cellIndex == 0) {
								stu.setName(cell.getStringCellValue());
								System.out.println(cell.getStringCellValue());
							}
							if(cellIndex == 1) {
								stu.setStuNum((int)cell.getNumericCellValue());
								System.out.println((int)cell.getNumericCellValue());
							}
							if(cellIndex == 2) {
								stu.setCla(cell.getStringCellValue()); 
								System.out.println(cell.getStringCellValue());
							}

						}
						list.add(stu);
					}

				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
//	public List<Student> readXlsx(File file) {
	public List<Student> readXlsx(String path) {
		List<Student> list = new ArrayList<>();
		InputStream inp;
		XSSFWorkbook workbook;
		try {
			inp = new FileInputStream(path);
			workbook = new XSSFWorkbook(inp);
			int size = workbook.getNumberOfSheets();
			System.out.println("工作表数:" + size);
			XSSFSheet sheet;
			for (int i = 0; i < size; i++) {
				sheet = workbook.getSheetAt(i);
				System.out.println("读取当前工作表名" + sheet.getSheetName());
				int rowNumber = sheet.getPhysicalNumberOfRows();
				System.out.println("有效行数:" + rowNumber);
				if (rowNumber == 0) {
					continue;
				} else {
					for (int rowIndex = 0; rowIndex < rowNumber; rowIndex++) {
						System.out.println("正在读取第" + (rowIndex + 1) + "行");
						if (rowIndex == 0) {
							continue;
						}
						XSSFRow row = sheet.getRow(rowIndex);
						Student stu = new Student();
						for (int cellIndex = 0; cellIndex < 3; cellIndex++) {
							XSSFCell cell = row.getCell(cellIndex);
							if(cellIndex == 0) {
								stu.setName(cell.getStringCellValue());
								System.out.println(cell.getStringCellValue());
							}
							if(cellIndex == 1) {
								stu.setStuNum((int)cell.getNumericCellValue());
								System.out.println((int)cell.getNumericCellValue());
							}
							if(cellIndex == 2) {
								stu.setCla(cell.getStringCellValue()); 
								System.out.println(cell.getStringCellValue());
							}						

						}
						list.add(stu);
					}

				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤实现: 1. 安装 `xlsx` 库: ```bash npm install xlsx --save ``` 2. 在 Vue3 的 TypeScript 项目中创建一个组件: ```vue <template> <div> <input type="file" ref="fileInput" @change="handleFileChange"> <iframe ref="iframe" style="display: none;"></iframe> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import * as XLSX from 'xlsx'; export default defineComponent({ methods: { async handleFileChange(event: Event) { const target = event.target as HTMLInputElement; const files = target.files; if (files && files.length > 0) { const file = files[0]; const reader = new FileReader(); reader.onload = (e) => { const data = e.target?.result as ArrayBuffer; const workbook = XLSX.read(data, { type: 'array' }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; const html = XLSX.utils.sheet_to_html(worksheet); const iframe = this.$refs.iframe as HTMLIFrameElement; iframe.srcdoc = html; iframe.style.display = 'block'; }; reader.readAsArrayBuffer(file); } }, }, }); </script> ``` 3. 在 `handleFileChange` 方法中,读取上Excel 文件,并将其解析为 `XLSX.WorkBook` 对象。然后,将第一个工作表转换为 HTML 字符串,并将其设置为 `iframe` 元素的 `srcdoc` 属性。最后,显示 `iframe` 元素。 4. 使用 `input` 元素上 Excel 文件,即可在页面上预览 Excel 文件。 注意:由于浏览器的安全限制,不能直接使用 JavaScript 访问本地文件系统,只能通过 `input` 元素上文件。另外,此方法只适用于生成简单的 HTML 表格,不支持 Excel 文件中的图表、图像等复杂元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值