| 
积分2915明经币 个注册时间2011-10-22在线时间 小时威望 金钱 个贡献 激情  
 | 
 
 发表于 2025-3-30 18:25:57
|
显示全部楼层 
| 借花献佛,分享在楼主源码基础上修改的导出csv的源码,感谢楼主的思路分享 
 public static class CsvExporter
 {
 public static void ExportToCsv(string excelFilePath)
 {
 try
 {
 // 检查文件是否存在
 if (!File.Exists(excelFilePath))
 {
 MessageBox.Show("Excel文件不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
 return;
 }
 
 // 确定CSV文件路径
 string csvFilePath = Path.ChangeExtension(excelFilePath, ".csv");
 
 // 读取Excel文件
 using (FileStream fs = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
 {
 HSSFWorkbook workbook = new HSSFWorkbook(fs);
 ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表
 
 // 创建StringBuilder来构建CSV内容
 StringBuilder csvContent = new StringBuilder();
 
 // 遍历每一行
 for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++)
 {
 IRow row = sheet.GetRow(rowIndex);
 if (row == null) continue;
 
 List<string> rowData = new List<string>();
 
 // 遍历每一列
 for (int colIndex = 0; colIndex < row.LastCellNum; colIndex++)
 {
 ICell cell = row.GetCell(colIndex);
 
 rowData.Add(GetCellValue(cell));
 }
 
 
 // 将行数据转换为CSV格式
 csvContent.AppendLine(string.Join(",", rowData.ToArray()));
 }
 
 // 写入CSV文件
 string csvContentStr = csvContent.ToString();
 byte[] bytes = Encoding.Default.GetBytes(csvContentStr);
 csvContentStr = Encoding.Default.GetString(bytes);
 
 File.WriteAllText(csvFilePath, csvContentStr, Encoding.Default);
 
 MessageBox.Show($"CSV文件已成功导出到:\n{csvFilePath}", "成功",
 MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
 }
 catch (Exception ex)
 {
 MessageBox.Show($"导出CSV文件时出错:\n{ex.Message}", "错误",
 MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
 }
 
 private static string GetCellValue(ICell cell)
 {
 if (cell == null) return "";
 
 switch (cell.CellType)
 {
 case CellType.String:
 return EscapeCsvValue(cell.StringCellValue);
 case CellType.Numeric:
 return cell.NumericCellValue.ToString();
 case CellType.Boolean:
 return cell.BooleanCellValue.ToString();
 case CellType.Formula:
 return GetCellValue(cell);
 default:
 return "";
 }
 }
 
 private static string EscapeCsvValue(string value)
 {
 if (value.Contains(",") || value.Contains("\"") || value.Contains("\n"))
 {
 return $"\"{value.Replace("\"", "\"\"")}\"";
 }
 return value;
 }
 }
 | 
 |