C# 解析 Excel 并且生成 Csv 文件代码分析
作者:omuying 发布时间:2021-11-09 18:04:04
今天工作中遇到一个需求,就是获取 excel 里面的内容,并且把 excel 另存为 csv,因为本人以前未接触过,所以下面整理出来的代码均来自网络,具体参考链接已丢失,原作者保留所有权利!
例子:
using System;
using System.Data;
namespace ExportExcelToCode
{
class ExcelOperater
{
public void Operater()
{
// Excel 路径
string excelPath = "";
// Csv 存放路径
string csvPath = "";
// 获取 Excel Sheet 名称列表
string[] sheetNameList = ExcelUtils.GetSheetNameList(excelPath);
if (sheetNameList != null && sheetNameList.Length > 0)
{
foreach (string sheetName in sheetNameList)
{
string itemName = sheetName.TrimEnd(new char[] { '$' });
// 解析 Excel 为 DataTable 对象
DataTable dataTable = ExcelUtils.ExcelToDataTable(excelPath, itemName);
if (dataTable != null && dataTable.Rows.Count > 0)
{
// 生成 Csv 文件
ExcelUtils.ExcelToCsv(excelPath, csvPath, itemName, "|#|", 0);
}
}
}
}
}
}
ExcelUtils.cs 文件
using System;
using System.Data;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExportExcelToCode
{
public partial class ExcelUtils
{
/// <summary>
/// 获取 Sheet 名称
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string[] GetSheetNameList(string filePath)
{
try
{
string connectionText = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
System.Data.OleDb.OleDbConnection oleDbConnection = new System.Data.OleDb.OleDbConnection(connectionText);
oleDbConnection.Open();
System.Data.DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); ;
string[] sheetNameList = new string[dataTable.Rows.Count];
for (int index = 0; index < dataTable.Rows.Count; index++)
{
sheetNameList[index] = dataTable.Rows[index][2].ToString();
}
oleDbConnection.Close();
return sheetNameList;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Excel 转 DataTable
/// </summary>
/// <param name="filePath"></param>
/// <param name="sheetName"></param>
/// <returns></returns>
public static System.Data.DataTable ExcelToDataTable(string filePath, string sheetName)
{
try
{
string connectionText = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
string selectText = string.Format("select * from [{0}$]", sheetName);
DataSet dataSet = new DataSet();
System.Data.OleDb.OleDbConnection oleDbConnection = new System.Data.OleDb.OleDbConnection(connectionText);
oleDbConnection.Open();
System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter = new System.Data.OleDb.OleDbDataAdapter(selectText, connectionText);
oleDbDataAdapter.Fill(dataSet, sheetName);
oleDbConnection.Close();
return dataSet.Tables[sheetName];
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Excel 转 Csv
/// </summary>
/// <param name="sourceExcelPathAndName"></param>
/// <param name="targetCSVPathAndName"></param>
/// <param name="excelSheetName"></param>
/// <param name="columnDelimeter"></param>
/// <param name="headerRowsToSkip"></param>
/// <returns></returns>
public static bool ExcelToCsv(string sourceExcelPathAndName, string targetCSVPathAndName, string excelSheetName, string columnDelimeter, int headerRowsToSkip)
{
Excel.Application oXL = null;
Excel.Workbooks workbooks = null;
Workbook mWorkBook = null;
Sheets mWorkSheets = null;
Worksheet mWSheet = null;
try
{
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false;
workbooks = oXL.Workbooks;
mWorkBook = workbooks.Open(sourceExcelPathAndName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
mWorkSheets = mWorkBook.Worksheets;
mWSheet = (Worksheet)mWorkSheets.get_Item(excelSheetName);
Excel.Range range = mWSheet.UsedRange;
Excel.Range rngCurrentRow;
for (int i = 0; i < headerRowsToSkip; i++)
{
rngCurrentRow = range.get_Range("A1", Type.Missing).EntireRow;
rngCurrentRow.Delete(XlDeleteShiftDirection.xlShiftUp);
}
range.Replace("\n", " ", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
range.Replace(",", columnDelimeter, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
mWorkBook.SaveAs(targetCSVPathAndName, Excel.XlFileFormat.xlCSV,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, false);
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
if (mWSheet != null) mWSheet = null;
if (mWorkBook != null) mWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
if (mWorkBook != null) mWorkBook = null;
if (oXL != null) oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
if (oXL != null) oXL = null;
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
}
}
需要特别指出的是:需要在项目中添加 Microsoft.Office.Interop.Excel.dll 文件,具体操作:选中引用->右键添加引用->浏览找到 Microsoft.Office.Interop.Excel,添加引用。
猜你喜欢
- 本文实例讲述了Java使用JDBC实现Oracle用户认证的方法。分享给大家供大家参考,具体如下:两天时间写的小品,以前的J2EE环境基本使
- private static void 某天的起始截止时间(DateTime 哪一天, out DateTime 起始时间, out Dat
- Spring Boot产生环形注入***************************APPLICATION FAILED TO STAR
- 前言前面文章讲了消息是如何保存的以及consumeQueue与Index文件更新机制。随着消息的增加,Broker不可能一直保存所有消息,B
- 项目结构把源码 clone 下来 , 可以看到 retrofit 整体结构如下图 http包目录下就是一些http协议常用接口 , 比如 请
- 本文实例讲述了C#从DataTable获取数据的方法。分享给大家供大家参考。具体如下:通过通用类,返回一个DataTable,要想显示每个单
- 上一篇介绍了使用springmvc集成shiro登陆过程,通过FormAuthenticationFilter过滤器获取到用户输入的账号密码
- 原理分析:迅雷的thunder://地址就是将普通url地址加前缀‘AA'、后缀‘ZZ',再base64编码后得到的字符串实
- 在本文中,我将向你展示c#编程的5个最佳实践。我从日常编程经验中学到了这些实践。我在release模式下测试了所有的代码,并在开发环境稳定后
- 首先是按行读取字符串import java.io.BufferedReader;import java.io.File;import jav
- 今天一位同事想写一个全屏幕截图的代码。当然要实现的第一步是能够获取整个屏幕的位图,记得Win32 API的CreateDC, BitBlt等
- 本文实例讲述了C#从画刷创建画笔的方法。分享给大家供大家参考。具体实现方法如下:using System;using System.Coll
- 说在前面大一软件工程在读,java萌新一只,第一次写博客,技术很菜勿喷。如有错误欢迎指出!这个小程序是给朋友的生日礼物,耗时半天,实际写起来
- 配置文件中设置通常在公司级别的项目中,我们可能会写多个application- dev/prod.yml ,然后我们通常会在applicat
- 摘要本文主要介绍基于SpringBoot定时任务ScheduledTaskRegistrar的动态扩展,实现定时任务的动态新增和删除。Sch
- 1.通过无参构造函数创建(默认)2.通过有参构造创建1.constructor 的index赋值<bean id="user
- 文章描述这个程序也记不清是什么时候写的了,犹记得那时我还很年轻,偶然从网上看到了这样一个类似的标题(AI五子棋的实现),进去后看到那个是ja
- 前言在你的工作中,有时候可能会看到 @Accessors(chain = true) 这样的注解,他是 lo
- 话不多说,先上图 &n
- 一、题目描述题目实现:运行服务器程序,等待客户端程序连接。二、解题思路首先需要在服务器中建立服务器套接字,并等待客户程序的连接。创建一个类: