C#-将一个文件夹(包含子文件夹)中的所有EXCEL表格转换成CSV格式文件
通过网盘分享的文件:ExcelToCsv.rar
链接: https://pan.baidu.com/s/1TtlJV2LzHMG9ac1Kx3xeAw?pwd=sky1 提取码: sky1
实现效果展示:
目标数据源 文件夹1
里面有一个1.xlsx,和demo文件夹,demo文件夹中存在一个2.xls Excel表格 如下图所示
操作
1、双击附件中的WindowsFormsApp1.exe
2、点击button按钮
3、选择Excel所在的文件夹目录 并确定
4、选择目标文件夹(CSV文件夹) 并确定
执行成功
代码
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConvert_Click(object sender, EventArgs e)
{
// 选择源文件夹
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
string sourceFolderPath = folderBrowserDialog.SelectedPath;
// 选择目标文件夹
using (FolderBrowserDialog destinationFolderBrowserDialog = new FolderBrowserDialog())
{
if (destinationFolderBrowserDialog.ShowDialog() == DialogResult.OK)
{
string destinationFolderPath = destinationFolderBrowserDialog.SelectedPath;
// 转换文件
ConvertExcelFilesToCsv(sourceFolderPath, destinationFolderPath);
MessageBox.Show("转换完成!");
}
}
}
}
}
private void ConvertExcelFilesToCsv(string sourceFolderPath, string destinationFolderPath)
{
try
{
var sourceFolder = sourceFolderPath;
var destinationFolder = destinationFolderPath;
var excelApp = new Excel.Application();
string[] files = Directory.GetFiles(sourceFolderPath, "*.xls*", SearchOption.AllDirectories);
files = files.Where(s => !s.Contains("~$")).ToArray();
foreach (var file in files)
{
// 打开工作簿
Workbook workbook = excelApp.Workbooks.Open(file);
// 构建目标CSV文件路径
string csvFilePath = Path.Combine(destinationFolderPath, Path.GetFileNameWithoutExtension(file) + ".csv");
// 保存为CSV格式
workbook.SaveAs(csvFilePath, XlFileFormat.xlCSV, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// 关闭工作簿
workbook.Close(false);
// 释放COM对象(可选,但推荐)
Marshal.ReleaseComObject(workbook);
}
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
MessageBox.Show("转换完成!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
本文来自博客园,作者:skystrivegao,转载请注明原文链接:https://www.cnblogs.com/skystrive/p/18602425
整理不易,如果对您有所帮助 请点赞收藏,谢谢~