- 积分
- 2803
- 明经币
- 个
- 注册时间
- 2011-10-22
- 在线时间
- 小时
- 威望
-
- 金钱
- 个
- 贡献
-
- 激情
-
|
借花献佛,分享在楼主源码基础上修改的导出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;
}
} |
|