zoukankan      html  css  js  c++  java
  • C# Winform Excel和CSV互转

     需要安装 office excel  
    
     
    
     public static class ExcelFormatHelper
        {
            /// <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.xlAddIn8, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    QuertExcel();
                  // ExcelFormatHelper.DeleteFile(FilePath);
    //可以不用杀掉进程
    QuertExcel();
     

    excelApplication.Quit();

    GC.WaitForPendingFinalizers();
    GC.Collect();


    } catch (Exception exc) { throw new Exception(exc.Message); }
           

    finally
    {
    GC.Collect();
    }

    return _NewFilePath;
            }
    
            /// <summary>
            /// 将xls文件转换为csv文件
            /// </summary>
            /// <param name="FilePath">文件全路路径</param>
            /// <returns>返回转换后的csv文件名</returns>
            public static string XLSSavesaCSV(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(".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);
                    QuertExcel();
                    //ExcelFormatHelper.DeleteFile(FilePath);
                }
                catch (Exception exc)
                {
                    throw new Exception(exc.Message);
                }
                return _NewFilePath;
            }
    
            /// <summary>
            /// 删除一个指定的文件
            /// </summary>
            /// <param name="FilePath">文件路径</param>
            /// <returns></returns>
            public static bool DeleteFile(string FilePath)
            {
                try
                {
                    bool IsFind = File.Exists(FilePath);
                    if (IsFind)
                    {
                        File.Delete(FilePath);
                    }
                    else
                    {
                        throw new IOException("指定的文件不存在");
                    }
                    return true;
                }
                catch (Exception exc)
                {
                    throw new Exception(exc.Message);
                }
               
            }
    
            /// <summary>
            /// 执行过程中可能会打开多个EXCEL文件 所以杀掉
            /// </summary>
            private static void QuertExcel()
            {
                Process[] excels = Process.GetProcessesByName("EXCEL");
                foreach (var item in excels)
                {
                    item.Kill();
                }         
            }
        }


    ----------------------------
    下面的方法比较好
    //将xml Excel转换为标准的CSV格式 
                Object Nothing = Missing.Value;//由于COM组件很多值需要用Missing.Value代替   
                Microsoft.Office.Interop.Excel.Application ExclApp = new Microsoft.Office.Interop.Excel.Application();// 初始化
                Microsoft.Office.Interop.Excel.Workbook ExclDoc = ExclApp.Workbooks.Open(savePath, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);//打开Excl工作薄   
                try
                {
                    Object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV;
                    ExclApp.DisplayAlerts = false;
                    ExclDoc.SaveAs(savePath.Replace("xls","csv"), format, Nothing, Nothing, Nothing, Nothing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
                }
                catch (Exception ex) { }

            ExclDoc.Close(Nothing, Nothing, Nothing);
            NAR(ExclDoc);
            ExclApp.Quit();
            NAR(ExclApp);


            
    GC.WaitForPendingFinalizers();

                 GC.Collect();

    /// <summary>
    /// 释放资源
    /// </summary>
    /// <param name="o"></param>
    private void NAR(object o)
    {
    try
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
    }
    catch { }
    finally
    {
    o = null;
    }
    }

    
    
    
    
    
     
  • 相关阅读:
    [Clojure] 包管理器leiningen配置国内镜像仓库
    [Haskell] 为什么列表操作++很昂贵?
    js判断除了空格换行之外是否为空
    iOS上架之隐私信息访问权限(uni-app)
    vue之动态绑定class
    this
    uni-app 上传图片之压缩图片上传
    uniapp无痛刷新token
    jQuery 发送跨域请求(jsonp)
    Document
  • 原文地址:https://www.cnblogs.com/junjie94wan/p/3094483.html
Copyright © 2011-2022 走看看