日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

教你C#將CSV轉為Excel的實現方法_C#教程

作者:E-iceblue ? 更新時間: 2022-05-28 編程語言

CSV(Comma Separated Values)文件是一種純文本文件,包含用逗號分隔的數據,常用于將數據從一個應用程序導入或導出到另一個應用程序。通過將CSV文件轉為EXCEL,可執行更多關于數據編輯、格式設置等操作。下面,將通過C#及VB.NET代碼展示如何來實現轉換。

一、程序環境

可通過以下途徑來安裝Excel庫:

1. 通過NuGet安裝Spire.XLS;

2. 官方下載包,解壓安裝到本地指定路徑。在Visual Studio中打開“解決方案資源管理器”,將本地安裝路徑下Bin文件夾下的dll添加引用至程序。

二、將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格式;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

欄目分類
最近更新