android实战项目开发七---完美解决excel文件导出功能,并分享到微信

因项目需求,需在Android中导出Excel文件并分享给微信好友。查询网上诸多方案,调试时均存在问题,文中给出关键代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于近期项目的需求,需要导出excel文件并分享给微信好友。基本上查询网上好多方案,单都没解决到位,调试的时候都有问题。

关键代码

private void exportExcel() {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        //设置列宽
        sheet.setColumnWidth(0,2000);
        sheet.setColumnWidth(1,3000);
        sheet.setColumnWidth(2,3000);
        sheet.setColumnWidth(3,3000);
        sheet.setColumnWidth(4,5000);
        sheet.setColumnWidth(5,7000);
        //=================================定义表头属性===============================================
        Font font = workbook.createFont(); // 生成字体格式设置对象
        font.setFontName("黑体"); // 设置字体黑体
        font.setBold(true); // 字体加粗
        font.setFontHeightInPoints(( short ) 16 ); // 设置字体大小
        font.setColor(Font.COLOR_NORMAL);//字体颜色

        CellStyle cellStyle = workbook.createCellStyle(); // 生成行格式设置对象
        cellStyle.setBorderBottom(BorderStyle.THIN);// 下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 横向居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 纵向居中对齐
        cellStyle.setFont(font);
        //=================================定义内容属性===============================================
        Font txtContent = workbook.createFont(); // 生成字体格式设置对象
        txtContent.setFontName("黑体"); // 设置字体黑体
        txtContent.setBold(false); // 字体加粗
        txtContent.setFontHeightInPoints(( short ) 12 ); // 设置字体大小
        txtContent.setColor(Font.COLOR_NORMAL);//字体颜色

        CellStyle cellStyleContent = workbook.createCellStyle(); // 生成行格式设置对象
        cellStyleContent.setBorderBottom(BorderStyle.THIN);// 下边框
        cellStyleContent.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyleContent.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyleContent.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyleContent.setAlignment(HorizontalAlignment.CENTER); // 横向居中对齐
        cellStyleContent.setVerticalAlignment(VerticalAlignment.CENTER); // 纵向居中对齐
        cellStyleContent.setFont(txtContent);

        //Font font = workbook.createFont();
        font.setBold(true);

        // 创建CellStyle并设置字体和对齐方式
        CellStyle style = workbook.createCellStyle();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        for (int k=0;k<list.size()+1;k++) {
            Row row = sheet.createRow(k);
            if (k==0){
                Cell cell0=row.createCell(0);
                Cell cell1=row.createCell(1);
                Cell cell2=row.createCell(2);
                Cell cell3=row.createCell(3);
                Cell cell4=row.createCell(4);

                row.setHeight((short) 500);
                cell0.setCellValue("姓名");
                cell1.setCellValue("类型");
                cell2.setCellValue("事由");
                cell3.setCellValue("金额");
                cell4.setCellValue("日期");

                cell0.setCellStyle(cellStyle);
                cell1.setCellStyle(cellStyle);
                cell2.setCellStyle(cellStyle);
                cell3.setCellStyle(cellStyle);
                cell4.setCellStyle(cellStyle);

            }else{
                Cell cell0=row.createCell(0);
                Cell cell1=row.createCell(1);
                Cell cell2=row.createCell(2);
                Cell cell3=row.createCell(3);
                Cell cell4=row.createCell(4);


                row.setHeight((short) 500);
                cell0.setCellValue(list.get(k-1).getName());
                cell1.setCellValue(list.get(k-1).getType());
                cell2.setCellValue(list.get(k-1).getEvent());
                cell3.setCellValue(list.get(k-1).getAmount());
                cell4.setCellValue(list.get(k-1).getRemembertime());

                cell0.setCellStyle(cellStyleContent);
                cell1.setCellStyle(cellStyleContent);
                cell2.setCellStyle(cellStyleContent);
                cell3.setCellStyle(cellStyleContent);
                cell4.setCellStyle(cellStyleContent);

            }
        }

        try {
            String fileName = Excel_File_Name;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
                values.put(MediaStore.Downloads.MIME_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);

                Uri uri = getActivity().getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
                if (uri != null) {
                    OutputStream outputStream = getActivity().getContentResolver().openOutputStream(uri);
                    if (outputStream != null) {
                        workbook.write(outputStream);
                        outputStream.close();
                        //Toast.makeText(getActivity(), "导出成功", Toast.LENGTH_SHORT).show();
                        ToastUtils.getInstance().showToast("导出成功");

                        // 分享Excel文件到微信
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND);
                        intent.setType("application/vnd.ms-excel"); // 设置文件类型为Excel
                        intent.putExtra(Intent.EXTRA_STREAM, uri); // 设置文件路径为Uri
                        startActivity(intent); // 启动分享意图
                    }
                }
            } else {
                String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + fileName;
                OutputStream outputStream = new FileOutputStream(filePath);
                workbook.write(outputStream);
                outputStream.close();
                //Toast.makeText(getActivity(), "导出成功", Toast.LENGTH_SHORT).show();
                ToastUtils.getInstance().showToast("导出成功");

                // 分享Excel文件到微信
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("application/vnd.ms-excel"); // 设置文件类型为Excel
                intent.putExtra(Intent.EXTRA_STREAM, filePath); // 设置文件路径为Uri
                startActivity(intent); // 启动分享意图
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

<think>好的,我现在需要处理用户关于自动化脚本开发的问题。用户希望了解相关的教程、工具和示例。首先,我要回顾用户提供的引用内容,看看有哪些信息可以利用。 引用[1]提到了Python自动化脚本的开发流程,包括需求分析、设计架构、编写代码、测试调试和部署上线,还有一些实践应用示例,比如文件处理、Web爬虫、邮件发送等。这些内容对用户来说应该很有帮助,特别是具体的案例,能让他们快速上手。 引用[2]是关于Ruby脚本和_工具的使用,包括模块化编写和代码复用的最佳实践,还有Ruby on Rails和Sinatra这样的框架。虽然用户可能主要关注Python,但Ruby也是一个不错的选择,特别是如果他们有兴趣的话。 引用[3]是Aseprite的脚本示例,可能涉及图像处理自动化。不过这可能比较特定,如果用户对游戏或图像处理感兴趣的话可以提及,否则可能不是重点。 引用[4]提到了Auto.js和VSCode插件,用于在电脑上开发手机自动化脚本。这对移动端自动化很有用,特别是Android用户,这部分内容应该详细介绍一下工具和开发流程。 用户之前的问题是想学习自动化脚本开发,现在需要教程、工具和示例。我需要综合这些引用,分门别类地整理出Python、Ruby、Auto.js等不同工具的技术栈,给出开发流程、工具推荐和示例,同时提供学习资源链接。 要注意用户可能更倾向于Python,因为引用[1]中的示例都是Python的,而Python在自动化领域也比较流行。但也要覆盖其他可能性,比如移动端用Auto.js,或者Ruby的场景。 需要确保回答结构清晰,分步骤说明,每个工具或语言单独成节,包含开发流程、工具、示例和学习资源。同时,生成相关问题时要围绕自动化脚本开发的扩展,比如性能优化、跨平台、调试工具等。 最后检查是否符合系统级指令:行内公式用$,独立公式用$$,正确使用LaTeX,中文回答,生成相关问题,引用标注正确。可能用户的问题中没有数学公式,但如果有需要的地方要正确应用。 现在开始组织内容,确保各部分逻辑清晰,工具和示例对应,引用正确标注,比如引用[1]、[4]等。同时,生成的问题要相关且有深度,帮助用户进一步探索。</think>### 自动化脚本开发技术指南 #### 一、核心开发流程(通用) 1. **需求分析** 明确脚本功能(如文件批量处理、数据采集、定时任务)和适用场景(桌面端/移动端)[^1]。 2. **工具选型** - 桌面端:Python($requests$, $pandas$)、Ruby - 移动端:Auto.js(Android自动化)[^4] - 专业工具:Aseprite脚本(图像处理)[^3] 3. **代码实现** ```python # Python示例:批量重命名文件 import os def batch_rename(path, prefix): for count, filename in enumerate(os.listdir(path)): new_name = f"{prefix}_{count}.txt" os.rename(os.path.join(path, filename), os.path.join(path, new_name)) ``` 4. **调试部署** 使用IDE断点调试(如VSCode),通过插件实现手机脚本热更新(Auto.js+VSCode)[^4]。 --- #### 二、主流技术栈详解 | 技术方向 | 推荐工具 | 典型场景 | 学习资源 | |---------------|---------------------------|---------------------------|-----------------------------| | **桌面自动化** | Python + Selenium | 网页操作/表单填写 | [Selenium官方文档](https://www.selenium.dev/) | | **数据处理** | Python + Pandas | Excel报表生成 | 《利用Python进行数据分析》 | | **移动端** | Auto.js + VSCode插件[^4] | 微信消息自动回复 | [Auto.js开源社区](https://autojs.org/) | | **图像处理** | Aseprite脚本[^3] | 游戏素材批量导出 | GitHub Aseprite脚本示例库 | --- #### 三、进阶开发技巧 1. **跨平台执行** 通过环境变量判断系统类型: ```python import platform if platform.system() == 'Windows': # Windows特定操作 elif platform.system() == 'Darwin': # macOS特定操作 ``` 2. **错误重试机制** 使用装饰器实现自动化容错: ```python from tenacity import retry, stop_after_attempt @retry(stop=stop_after_attempt(3)) def unstable_api_call(): # 可能失败的操作 ``` 3. **性能优化** 多线程处理IO密集型任务: ```python from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=4) as executor: executor.map(process_file, file_list) ``` --- #### 四、典型应用案例 1. **Web自动化测试** ```python from selenium import webdriver driver = webdriver.Chrome() driver.get("https://example.com") search_box = driver.find_element("name", "q") search_box.send_keys("自动化测试") ``` 2. **手机自动化脚本(Auto.js)** ```javascript // 自动发送微信消息 launchApp("微信"); click("通讯录"); click("好友名称"); setText("你好,这是自动消息"); click("发送"); ``` 3. **Aseprite图像批处理[^3]** ```lua -- 批量导出图层为PNG for _, layer in ipairs(app.activeSprite.layers) do app.command.ExportLayerAsPNG{ layer=layer } end ``` --- #### 五、学习资源推荐 1. **Python自动化** - 官方教程:[Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) - 实战项目:GitHub搜索「automation-scripts」 2. **移动端开发** - Auto.js开发文档:[VSCode插件使用指南](https://github.com/hyb1996/Auto.js-VSCode-Extension)[^4] 3. **专业领域** - Aseprite脚本开发:[官方示例库](https://github.com/aseprite/Aseprite-Script-Examples)[^3] ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值