软件编程
位置:首页>> 软件编程>> C#编程>> 教你C#将CSV转为Excel的实现方法

教你C#将CSV转为Excel的实现方法

作者:E-iceblue  发布时间:2021-09-18 00:42:03 

标签:C#,CSV,Excel

CSV(Comma Separated Values)文件是一种纯文本文件,包含用逗号分隔的数据,常用于将数据从一个应用程序导入或导出到另一个应用程序。通过将CSV文件转为EXCEL,可执行更多关于数据编辑、格式设置等操作。下面,将通过C#及VB.NET代码展示如何来实现转换。

一、程序环境

可通过以下途径来安装Excel库:

1. 通过NuGet安装Spire.XLS;

2. 官方下载包,解压安装到本地指定路径。在Visual Studio中打开“解决方案资源管理器”,将本地安装路径下Bin文件夹下的dll添加引用至程序。

教你C#将CSV转为Excel的实现方法

二、将CSV转为Excel

C#

using Spire.Xls;

namespace CSVtoExcel_XLS
{
   class Program
   {
       static void Main(string[] args)
       {
           //加载CSV文件
           Workbook workbook = new Workbook();
           workbook.LoadFromFile("test.csv", ",", 1, 1);
           //获取第一个工作表
           Worksheet sheet = workbook.Worksheets[0];
           //访问工作表中使用的范围
           CellRange usedRange = sheet.AllocatedRange;
           //当将范围内的数字保存为文本时,忽略错误
           usedRange.IgnoreErrorOptions = IgnoreErrorType.NumberAsText;
           //自适应行高、列宽
           usedRange.AutoFitColumns();
           usedRange.AutoFitRows();
           //保存文档
           workbook.SaveToFile("result.xlsx", ExcelVersion.Version2013);
           System.Diagnostics.Process.Start("result.xlsx");
       }
   }
}

VB.NET

Imports Spire.Xls

Namespace CSVtoExcel_XLS
   Class Program
       Private Shared Sub Main(args As String())
           '加载CSV文件
           Dim workbook As New Workbook()
           workbook.LoadFromFile("test.csv", ",", 1, 1)
           '获取第一个工作表
           Dim sheet As Worksheet = workbook.Worksheets(0)
           '访问工作表中使用的范围
           Dim usedRange As CellRange = sheet.AllocatedRange
           '当将范围内的数字保存为文本时,忽略错误
           usedRange.IgnoreErrorOptions = IgnoreErrorType.NumberAsText
           '自适应行高、列宽
           usedRange.AutoFitColumns()
           usedRange.AutoFitRows()
           '保存文档
           workbook.SaveToFile("result.xlsx", ExcelVersion.Version2013)
           System.Diagnostics.Process.Start("result.xlsx")
       End Sub
   End Class
End Namespace

教你C#将CSV转为Excel的实现方法

补充知识:C# .csv文件转为Excel格式;Excel格式转换为.csv,代码如下所示:

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Excel=Microsoft.Office.Interop.Excel;

namespace WinFromAPP
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }
       /// <summary>
       /// 将Csv文件转换为XLS文件
       /// </summary>
       /// <param name="FilePath">文件全路路径</param>
       /// <returns>返回转换后的Xls文件名</returns>
       public static string CSVSaveasXLS(string FilePath)
           QuertExcel();
           string _NewFilePath = "";
           Excel.Application excelApplication;
           Excel.Workbooks excelWorkBooks = null;
           Excel.Workbook excelWorkBook = null;
           Excel.Worksheet excelWorkSheet = null;
           try
           {
               excelApplication = new Excel.ApplicationClass();
               excelWorkBooks = excelApplication.Workbooks;
               excelWorkBook = ((Excel.Workbook)excelWorkBooks.Open(FilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));
               excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[1];
               excelApplication.Visible = false;
               excelApplication.DisplayAlerts = false;
               _NewFilePath = FilePath.Replace(".csv", ".xls");
               excelWorkBook.SaveAs(_NewFilePath, Excel.XlFileFormat.xlAddIn, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
               excelWorkBook.Close();
               QuertExcel();
               // ExcelFormatHelper.DeleteFile(FilePath);
               //可以不用杀掉进程QuertExcel();
               GC.Collect(System.GC.GetGeneration(excelWorkSheet));
               GC.Collect(System.GC.GetGeneration(excelWorkBook));
               GC.Collect(System.GC.GetGeneration(excelApplication));
           }
           catch (Exception exc)
               throw new Exception(exc.Message);
           finally
               GC.Collect();
           return _NewFilePath;
       /// 将xls文件转换为csv文件
       /// <returns>返回转换后的csv文件名</returns>
       public static string XLSSavesaCSV(string FilePath)
               _NewFilePath = FilePath.Replace(".xls", ".csv");
               // excelWorkSheet._SaveAs(FilePath, Excel.XlFileFormat.xlCSVWindows, Missing.Value, Missing.Value, Missing.Value,Missing.Value,Missing.Value, Missing.Value, Missing.Value);
               excelWorkBook.SaveAs(_NewFilePath, Excel.XlFileFormat.xlCSV, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
               //ExcelFormatHelper.DeleteFile(FilePath);
       /// 删除一个指定的文件
       /// <param name="FilePath">文件路径</param>
       /// <returns></returns>
       public static bool DeleteFile(string FilePath)
               bool IsFind = File.Exists(FilePath);
               if (IsFind)
               {
                   File.Delete(FilePath);
               }
               else
                   throw new IOException("指定的文件不存在");
               return true;
       /// 执行过程中可能会打开多个EXCEL文件 所以杀掉
       private static void QuertExcel()
           Process[] excels = Process.GetProcessesByName("EXCEL");
           foreach (var item in excels)
               item.Kill();
       private void btnConvert_Click(object sender, EventArgs e)
           //CSVSaveasXLS(textBox1.Text);
           XLSSavesaCSV(textBox1.Text);
   }
}

来源:https://www.cnblogs.com/Yesi/p/16054552.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com