使用XML创建Excel文档-.NET教程,XML应用 http://www.z6688.com/info/47612-1.htm

本文介绍了一种使用C#创建Excel文件的方法,该方法利用XML格式化字符串直接生成Excel文档,无需安装Excel应用程序。通过实例展示了如何创建表格、填充数据及设置文件属性。
文章页数:[1] 
 

原例子使用vb.net写的,以下的用c#改写的代码

原文代码:

http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=ddbaecb9-a260-4656-9f22-300b6a1ce66c

本例使用xml来创建excel文档,但在运行时不需要安装excel程序。

            dataset mdsdata = new dataset();
            mdsdata.tables.add("mytable");

            mdsdata.tables["mytable"].columns.add("id");
            mdsdata.tables["mytable"].columns.add("name");
            mdsdata.tables["mytable"].columns.add("password");

            for (int i = 0; i < 10; i++)
            {
                datarow dr = mdsdata.tables["mytable"].newrow();
                dr["id"] = i;
                dr["name"] = i;
                dr["password"] = i;
                mdsdata.tables["mytable"].rows.add(dr);
            }

            savefiledialog dialog1 = new savefiledialog();
            dialog1.addextension = true;
            dialog1.checkpathexists = true;
            dialog1.filter = "excel workbooks (*.xls) | *.xls";
            dialog1.overwriteprompt = true;
            dialog1.title = "save excel formatted report";
            if (dialog1.showdialog() == dialogresult.ok)
            {
                int num2 = 0;
                int num3 = mdsdata.tables[0].rows.count + 1;
                int num1 = mdsdata.tables[0].columns.count;
                num2 = 0;
                string text1 = dialog1.filename;
                if (file.exists(text1))
                {
                    file.delete(text1);
                }
                streamwriter writer1 = new streamwriter(text1, false);
                streamwriter writer2 = writer1;
                writer2.writeline("<?xml version=/"1.0/"?>");
                writer2.writeline("<?mso-application progid=/"excel.sheet/"?>");
                writer2.writeline("<workbook xmlns=/"urn:schemas-microsoft-com:office:spreadsheet/"");
                writer2.writeline(" xmlns:o=/"urn:schemas-microsoft-com:office:office/"");
                writer2.writeline(" xmlns:x=/"urn:schemas-microsoft-com:office:excel/"");
                writer2.writeline(" xmlns:ss=/"urn:schemas-microsoft-com:office:spreadsheet/"");
                writer2.writeline(" xmlns:html=/"http://www.w3.org/tr/rec-html40/">");
                writer2.writeline(" <documentproperties xmlns=/"urn:schemas-microsoft-com:office:office/">");
                writer2.writeline("  <author>automated report generator example</author>");
                writer2.writeline(string.format("  <created>{0}t{1}z</created>", datetime.now.tostring("yyyy-mm-dd"), datetime.now.tostring("hh:mm:ss")));
                writer2.writeline("  <company>your company here</company>");
                writer2.writeline("  <version>11.6408</version>");
                writer2.writeline(" </documentproperties>");
                writer2.writeline(" <excelworkbook xmlns=/"urn:schemas-microsoft-com:office:excel/">");
                writer2.writeline("  <windowheight>8955</windowheight>");
                writer2.writeline("  <windowwidth>11355</windowwidth>");
                writer2.writeline("  <windowtopx>480</windowtopx>");
                writer2.writeline("  <windowtopy>15</windowtopy>");
                writer2.writeline("  <protectstructure>false</protectstructure>");
                writer2.writeline("  <protectwindows>false</protectwindows>");
                writer2.writeline(" </excelworkbook>");
                writer2.writeline(" <styles>");
                writer2.writeline("  <style ss:id=/"default/" ss:name=/"normal/">");
                writer2.writeline("   <alignment ss:vertical=/"bottom/"/>");
                writer2.writeline("   <borders/>");
                writer2.writeline("   <font/>");
                writer2.writeline("   <interior/>");
                writer2.writeline("   <protection/>");
                writer2.writeline("  </style>");
                writer2.writeline("  <style ss:id=/"s21/">");
                writer2.writeline("   <alignment ss:vertical=/"bottom/" ss:wraptext=/"1/"/>");
                writer2.writeline("  </style>");
                writer2.writeline(" </styles>");
                writer2.writeline(" <worksheet ss:name=/"myreport/">");
                writer2.writeline(string.format("  <table ss:expandedcolumncount=/"{0}/" ss:expandedrowcount=/"{1}/" x:fullcolumns=/"1/"", num1.tostring(), num3.tostring()));
                writer2.writeline("   x:fullrows=/"1/">");
                foreach (datarow row1 in mdsdata.tables[0].rows)
                {
                    writer2.writeline("<row>");
                    for (num2 = 0; num2 != num1; num2++)
                    {
                        writer2.write("<cell ss:styleid=/"s21/"><data ss:type=/"string/">");
                        writer2.write(row1[num2].tostring());
                        writer2.writeline("</data></cell>");
                    }
                    writer2.writeline("</row>");
                }
                writer2.writeline("  </table>");
                writer2.writeline("  <worksheetoptions xmlns=/"urn:schemas-microsoft-com:office:excel/">");
                writer2.writeline("   <selected/>");
                writer2.writeline("   <panes>");
                writer2.writeline("    <pane>");
                writer2.writeline("     <number>3</number>");
                writer2.writeline("     <activerow>1</activerow>");
                writer2.writeline("    </pane>");
                writer2.writeline("   </panes>");
                writer2.writeline("   <protectobjects>false</protectobjects>");
                writer2.writeline("   <protectscenarios>false</protectscenarios>");
                writer2.writeline("  </worksheetoptions>");
                writer2.writeline(" </worksheet>");
                writer2.writeline(" <worksheet ss:name=/"sheet2/">");
                writer2.writeline("  <worksheetoptions xmlns=/"urn:schemas-microsoft-com:office:excel/">");
                writer2.writeline("   <protectobjects>false</protectobjects>");
                writer2.writeline("   <protectscenarios>false</protectscenarios>");
                writer2.writeline("  </worksheetoptions>");
                writer2.writeline(" </worksheet>");
                writer2.writeline(" <worksheet ss:name=/"sheet3/">");
                writer2.writeline("  <worksheetoptions xmlns=/"urn:schemas-microsoft-com:office:excel/">");
                writer2.writeline("   <protectobjects>false</protectobjects>");
                writer2.writeline("   <protectscenarios>false</protectscenarios>");
                writer2.writeline("  </worksheetoptions>");
                writer2.writeline(" </worksheet>");
                writer2.writeline("</workbook>");
                writer2 = null;
                writer1.close();
                messagebox.show("report created", "success", messageboxbuttons.ok, messageboxicon.asterisk);
            }



文章整理:西部数码--专业提供 域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!
 
package com.shunyu.yiwu.ai.platform.controller; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.http.*; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * 文件下载控制器 */ @RestController @RequestMapping("/file/download") @Tag(name = "文件下载", description = "处理文件下载相关接口") public class FileDownloadController { private final ResourcePatternResolver resourcePatternResolver; public FileDownloadController(ResourcePatternResolver resourcePatternResolver) { this.resourcePatternResolver = resourcePatternResolver; } /** * 下载帮助文档(默认返回目录下第一个文件) */ @GetMapping("/help-doc") public ResponseEntity<byte[]> downloadHelpDoc() { try { // 获取help-docs目录下的所有文件 Resource[] resources = resourcePatternResolver.getResources("classpath:help-docs/*"); if (resources.length == 0) { return ResponseEntity.notFound().build(); } // 获取第一个文件(按文件名排序以确保一致性) List<Resource> resourceList = Arrays.asList(resources); resourceList.sort((r1, r2) -> { try { return Objects.requireNonNull(r1.getFilename()).compareTo(Objects.requireNonNull(r2.getFilename())); } catch (Exception e) { return 0; } }); Resource fileResource = resourceList.get(0); String filename = fileResource.getFilename(); // 读取文件内容 byte[] fileContent; try (InputStream inputStream = fileResource.getInputStream()) { fileContent = inputStream.readAllBytes(); // 使用更可靠的读取方式 } // 检测内容类型 String contentType = detectContentTypeFromName(filename); // 对于Office Open XML格式文件,使用通用二进制流类型以避免编码问题 if (filename != null && (filename.toLowerCase().endsWith(".docx") || filename.toLowerCase().endsWith(".xlsx") || filename.toLowerCase().endsWith(".pptx"))) { contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; } // 对文件名进行UTF-8编码 String encodedFileName = null; if (filename != null) { encodedFileName = URLEncoder.encode(filename, StandardCharsets.UTF_8) .replace("+", "%20"); } // 构建响应 return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName) .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION) .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") .header(HttpHeaders.PRAGMA, "no-cache") .header(HttpHeaders.EXPIRES, "0") .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileContent.length)) .body(fileContent); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } /** * 根据文件名检测Content-Type */ private String detectContentTypeFromName(String filename) { if (filename == null) { return MediaType.APPLICATION_OCTET_STREAM_VALUE; } String fileName = filename.toLowerCase(); if (fileName.endsWith(".pdf")) { return "application/pdf"; } else if (fileName.endsWith(".doc")) { return "application/msword"; } else if (fileName.endsWith(".docx")) { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } else if (fileName.endsWith(".xls")) { return "application/vnd.ms-excel"; } else if (fileName.endsWith(".xlsx")) { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else if (fileName.endsWith(".ppt")) { return "application/vnd.ms-powerpoint"; } else if (fileName.endsWith(".pptx")) { return "application/vnd.openxmlformats-officedocument.presentationml.presentation"; } else if (fileName.endsWith(".txt")) { return "text/plain; charset=UTF-8"; } else if (fileName.endsWith(".html") || fileName.endsWith(".htm")) { return "text/html; charset=UTF-8"; } else if (fileName.endsWith(".css")) { return "text/css; charset=UTF-8"; } else if (fileName.endsWith(".js")) { return "application/javascript"; } else if (fileName.endsWith(".json")) { return "application/json; charset=UTF-8"; } else if (fileName.endsWith(".xml")) { return "application/xml; charset=UTF-8"; } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { return "image/jpeg"; } else if (fileName.endsWith(".png")) { return "image/png"; } else if (fileName.endsWith(".gif")) { return "image/gif"; } else if (fileName.endsWith(".svg")) { return "image/svg+xml"; } else if (fileName.endsWith(".zip")) { return "application/zip"; } else if (fileName.endsWith(".rar")) { return "application/vnd.rar"; } else if (fileName.endsWith(".7z")) { return "application/x-7z-compressed"; } else { return MediaType.APPLICATION_OCTET_STREAM_VALUE; } } }以上的代码经过我的下载测试,我发现了下载的文件是docx格式会出现乱码现象,下载pdf格式会出现空白页面,下载xlsx格式跟源文件保持一致,下载txt格式跟源文件保持一致. 请进行解决
最新发布
08-27
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值