CSharp: Convert CSV to XLS Using Open XML SDK

news/2025/10/23 19:52:33/文章来源:https://www.cnblogs.com/geovindu/p/19161493
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Globalization;
using CsvHelper;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;namespace CsvToXlsConverter
{class Program{static void Main(string[] args){try{// Parse command line argumentsstring inputPath = null;string outputPath = null;Encoding encoding = Encoding.UTF8;char delimiter = ',';for (int i = 0; i < args.Length; i++){switch (args[i].ToLower()){case "-i":case "--input":if (i + 1 < args.Length)inputPath = args[++i];break;case "-o":case "--output":if (i + 1 < args.Length)outputPath = args[++i];break;case "-e":case "--encoding":if (i + 1 < args.Length){string encodingName = args[++i];try{encoding = Encoding.GetEncoding(encodingName);}catch{Console.WriteLine($"Warning: Unsupported encoding '{encodingName}'. Using default UTF-8.");}}break;case "-d":case "--delimiter":if (i + 1 < args.Length){string delimiterStr = args[++i];if (delimiterStr.Length == 1)delimiter = delimiterStr[0];else if (delimiterStr.Equals("tab", StringComparison.OrdinalIgnoreCase))delimiter = '\t';elseConsole.WriteLine($"Warning: Unsupported delimiter '{delimiterStr}'. Using default comma.");}break;case "-h":case "--help":ShowHelp();return;}}// Validate input and output pathsif (string.IsNullOrEmpty(inputPath))throw new ArgumentException("Input file path is required. Use -i or --input option.");if (string.IsNullOrEmpty(outputPath))outputPath = Path.ChangeExtension(inputPath, ".xls");if (!File.Exists(inputPath))throw new FileNotFoundException("Input file not found.", inputPath);// Check if output directory existsstring outputDirectory = Path.GetDirectoryName(outputPath);if (!string.IsNullOrEmpty(outputDirectory) && !Directory.Exists(outputDirectory))Directory.CreateDirectory(outputDirectory);// Convert CSV to XLSConsole.WriteLine("CSV to XLS Converter");Console.WriteLine("====================");Console.WriteLine($"Input file: {inputPath}");Console.WriteLine($"Output file: {outputPath}");Console.WriteLine($"Encoding: {encoding.EncodingName}");Console.WriteLine($"Delimiter: {(delimiter == '\t' ? "Tab" : delimiter.ToString())}");Console.WriteLine();DateTime startTime = DateTime.Now;try{// Read CSVConsole.WriteLine("Reading CSV file...");DataTable dataTable = ReadCsv(inputPath, encoding, delimiter);Console.WriteLine($"Successfully read {dataTable.Rows.Count} rows and {dataTable.Columns.Count} columns.");// Convert to XLSConsole.WriteLine("Converting to XLS format...");ConvertDataTableToXls(dataTable, outputPath);TimeSpan duration = DateTime.Now - startTime;Console.WriteLine();Console.WriteLine($"Conversion completed successfully in {duration.TotalSeconds:F2} seconds.");Console.WriteLine($"Output file saved to: {outputPath}");}catch (Exception ex){Console.WriteLine();throw new Exception($"Conversion failed: {ex.Message}", ex);}}catch (Exception ex){Console.WriteLine($"Error: {ex.Message}");Console.WriteLine();Console.WriteLine("Use --help for usage information.");}}/// <summary>/// Reads a CSV file and returns its contents as a DataTable/// </summary>public static DataTable ReadCsv(string filePath, Encoding encoding, char delimiter){try{using (var reader = new StreamReader(filePath, encoding))using (var csv = new CsvReader(reader, new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture){Delimiter = delimiter.ToString(),HasHeaderRecord = true,IgnoreBlankLines = true,TrimOptions = CsvHelper.Configuration.TrimOptions.Trim})){using (var dr = new CsvDataReader(csv)){var dt = new DataTable();dt.Load(dr);return dt;}}}catch (Exception ex){throw new Exception($"Failed to read CSV file: {ex.Message}", ex);}}/// <summary>/// Converts a DataTable to an XLS file using Open XML SDK/// </summary>public static void ConvertDataTableToXls(DataTable dataTable, string outputPath){try{// Create a new spreadsheet documentusing (SpreadsheetDocument document = SpreadsheetDocument.Create(outputPath, SpreadsheetDocumentType.Workbook)){// Add a WorkbookPart to the documentWorkbookPart workbookPart = document.AddWorkbookPart();workbookPart.Workbook = new Workbook();// Add a WorksheetPart to the WorkbookPartWorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();worksheetPart.Worksheet = new Worksheet(new SheetData());// Add Sheets to the WorkbookSheets sheets = workbookPart.Workbook.AppendChild(new Sheets());// Append a new worksheet and associate it with the workbookSheet sheet = new Sheet(){Id = workbookPart.GetIdOfPart(worksheetPart),SheetId = 1,Name = "Sheet1"};sheets.Append(sheet);// Get the SheetData objectSheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();// Add header rowRow headerRow = new Row();foreach (DataColumn column in dataTable.Columns){Cell cell = CreateCell(column.ColumnName, CellValues.String);headerRow.AppendChild(cell);}sheetData.AppendChild(headerRow);// Add data rowsforeach (DataRow row in dataTable.Rows){Row dataRow = new Row();foreach (var item in row.ItemArray){CellValues cellType = GetCellValueType(item);string cellValue = GetCellValueAsString(item, cellType);Cell cell = CreateCell(cellValue, cellType);dataRow.AppendChild(cell);}sheetData.AppendChild(dataRow);}// Save the workbookworkbookPart.Workbook.Save();}}catch (Exception ex){throw new Exception($"Failed to create XLS file: {ex.Message}", ex);}}/// <summary>/// Creates a new Excel cell with the specified value and type/// </summary>private static Cell CreateCell(string value, CellValues cellType){Cell cell = new Cell();cell.DataType = new EnumValue<CellValues>(cellType);cell.CellValue = new CellValue(value);return cell;}/// <summary>/// Determines the cell value type based on the object type/// </summary>private static CellValues GetCellValueType(object value){if (value == DBNull.Value)return CellValues.String;Type type = value.GetType();if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte))return CellValues.Number;else if (type == typeof(float) || type == typeof(double) || type == typeof(decimal))return CellValues.Number;else if (type == typeof(DateTime))return CellValues.Date;else if (type == typeof(bool))return CellValues.Boolean;elsereturn CellValues.String;}/// <summary>/// Converts an object to its string representation based on the cell type/// </summary>private static string GetCellValueAsString(object value, CellValues cellType){if (value == DBNull.Value)return string.Empty;switch (cellType){case CellValues.Boolean:return (bool)value ? "1" : "0";case CellValues.Date:DateTime dateValue = (DateTime)value;// Excel stores dates as OLE Automation datesreturn dateValue.ToOADate().ToString(CultureInfo.InvariantCulture);case CellValues.Number:return Convert.ToString(value, CultureInfo.InvariantCulture);default:return Convert.ToString(value);}}/// <summary>/// Shows help information/// </summary>private static void ShowHelp(){Console.WriteLine("CSV to XLS Converter");Console.WriteLine("Converts CSV files to XLS (Excel 97-2003) format using Open XML SDK.");Console.WriteLine();Console.WriteLine("Usage: CsvToXlsConverter [options]");Console.WriteLine();Console.WriteLine("Options:");Console.WriteLine("  -i, --input      Input CSV file path (required)");Console.WriteLine("  -o, --output     Output XLS file path (optional, defaults to input path with .xls extension)");Console.WriteLine("  -e, --encoding   Encoding of the CSV file (optional, defaults to UTF-8)");Console.WriteLine("                   Examples: UTF-8, ASCII, Windows-1252, etc.");Console.WriteLine("  -d, --delimiter  Field delimiter character (optional, defaults to comma)");Console.WriteLine("                   Use 'tab' for tab-delimited files");Console.WriteLine("  -h, --help       Show this help message");Console.WriteLine();Console.WriteLine("Examples:");Console.WriteLine("  CsvToXlsConverter -i data.csv");Console.WriteLine("  CsvToXlsConverter -i input.csv -o output.xls");Console.WriteLine("  CsvToXlsConverter -i data.tsv -d tab -e Windows-1252");}}
}

  

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/944633.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

实用指南:PyTorch 数据处理工具箱:从数据加载到可视化的完整指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

《程序员修炼之道:从小工到专家》阅读笔记1

2025年的今天,当AI代码助手能自动生成70%基础代码时,程序员的核心竞争力究竟是什么?《程序员修炼之道》序言以"生存指南"的定位给出震撼答案:真正的高手从不依赖工具,而是凭借责任意识、持续学习与批判…

多级多卡训练模型时有些参数没有参与loss计算和梯度更新的解决办法

在运行程序的bash命令中添加 export TORCH_DISTRIBUTED_DEBUG=DETAIL ,这样就可以在log或终端打印没有参与loss计算的权重参数了。

负载均衡及三种软件负载

[!TIP] 环境用nginx反向代理文档里的三台服务器即可一、基于nginx的负载均衡 七层负载:配置nginx.conf主配置文件 vim /etc/nginx/nginx.conf 在http块内添加: upstream userLB(随意){ #server写的ip:端口号(8080为t…

在 GEO / AIO 角度:如何优化 SEO 内容?

一、先把优化方向说清楚 现在做内容的目标不仅仅是 SEO 排第几,而是被选进 AI 答案。 AI 搜索会把页面切成可复用的小块,再按权威与相关性拼答案。传统 SEO 的可抓取、元数据、内链、外链仍是地基,但想被选中,核心…

Android Handler的runWithScissors手段

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

Idea提高制作效率的快捷键最佳学习方式

Idea提高制作效率的快捷键最佳学习方式pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Mon…

Elasticsearch8容器化部署 - 实践

Elasticsearch8容器化部署 - 实践2025-10-23 19:30 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !impor…

ski 和 db 模块的通信

ski 和 db 模块的通信 qt 信号槽 创建一个单例类,在 db 模块发送信号,在ski 模块接收 class abSignalEmitter : public QObject {Q_OBJECTpublic:static abSignalEmitter& instance() {static abSignalEmitter i…

rocky10自己手动换源

rocky10手动换源 动作背景:自己做小实验需要inistall ,但是安装之后配置的源文件有问题,报错 流程: 1.先确认系统版本 cat /etc/rocky-release 2.备份原有配置(必要动作) mkdir -p /etc/yum.repos.d/backup mv /…

完整教程:ImmuCellAI 免疫浸润分析

完整教程:ImmuCellAI 免疫浸润分析pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco…

4.6.2版本来了!快来看看新版本有哪些改动

产品更新概览 功能修复: 修复云托管自定义日期无法设置问题; 修复资产库中放置模式使用问题; 修复鲸孪生中gltf格式模型无法添加到资产库问题; 修复鲸孪生中已知情况下fbx模型导入失败问题; 修复菜单组件首次触发…

2025-10-22 ZR-J 模拟赛 赛后总结【ZR】

光速打完前三题,然后被 T4 击败。 结果挂完了。 50+10+100+0。 T1 Letters 题意 给定 \(n\) 个单词,对于这些单词组成的集合的所有子集,问这些子集中 a 到 z 26 个字母均出现过至少一次的子集总数。 赛时 经过 0 秒…

Deepoc具身智能模型:为传统机器人注入“灵魂”,重塑建筑施工现场安全新范式 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

[grep] grep stream 2, the error message

In Unix-like systems, stdout (standard output) is stream 1, and stderr (standard error) is stream 2. By default, grep reads from stdin, which typically receives stdout — not stderr. To have grep searc…

P5285 [十二省联考 2019] 骗分过样例

绝世好题P5285 [十二省联考 2019] 骗分过样例 题目链接 前言 一道很考验数论水平、耐心与注意力的题 \(16\) 个测试点中有 \(14\) 个是我独立完成的,剩余的测试点 #7,#13 分别参考了题解和讨论区题目大意 下发 \(16\…

Liferay Portal与DXP集合提供程序存在授权缺失漏洞分析

本文详细分析了CVE-2025-62247漏洞,该漏洞影响Liferay Portal和DXP的集合提供程序组件,存在授权缺失问题,允许实例用户跨实例读取和选择未经授权的蓝图配置。Liferay Portal和DXP集合提供程序存在授权缺失漏洞 漏洞…

MapGIS Objects Java计算一条三维线段与一个三角形所在的平面的交点 - 教程

MapGIS Objects Java计算一条三维线段与一个三角形所在的平面的交点 - 教程pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-famil…

layui时间与日期选择器,时间范围查询数据,后端springboot

需求 我需要根据时间段,比如10.1号——10月31号,查询此时间段的对应数据。 实体类 user:含有姓名,性别。其中有个入职时间private Date interviewTime; 我们需要根据入职时间,查询指定范围的数据 前端<div cla…

读书笔记:OpenPBR 规范(2)

3. 模型 ​ ​​​  使用前述的公式和参数化方法,我们现在来具体说明 OpenPBR 表面模型的结构。我们首先描述“非薄壁”情况(“薄壁”情况下的结构有所不同),其材质结构非正式地如下图所示:​ ​​​  总而言…