zoukankan      html  css  js  c++  java
  • 常用类-excel转csv

       public class ExcelFileHelper
        {
            public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
            {
    
                using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    IExcelDataReader reader = null;
                    if (excelFilePath.EndsWith(".xls"))
                    {
                        reader = ExcelReaderFactory.CreateBinaryReader(stream);
                    }
                    else if (excelFilePath.EndsWith(".xlsx"))
                    {
                        reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                    }
    
                    if (reader == null)
                        return false;
    
                    var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = false
                        }
                    });
    
                    var csvContent = string.Empty;
                    int row_no = 0;
                    while (row_no < ds.Tables[0].Rows.Count)
                    {
                        var arr = new List<string>();
                        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                        {
                            arr.Add(ds.Tables[0].Rows[row_no][i].ToString());//需要做处理
                        }
                        row_no++;
                        csvContent += string.Join(",", arr.ToArray()) + "
    ";
                    }
                    StreamWriter csv = new StreamWriter(destinationCsvFilePath, false,Encoding.UTF8);
                    csv.Write(csvContent);
                    csv.Close();
                    return true;
                }
            }
        }

    需要安装包:

    <packages>
      <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
      <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
    </packages>
  • 相关阅读:
    Oracle expdp impdp中 exclude/include 的使用
    Oracle表空间迁移Move Tablespace
    m2ewtp的作用
    有意思的排序算法合并排序
    有意思的排序算法插入排序
    equals与“==”之惑
    简化的打印语句静态导入
    有意思的排序算法堆排序
    博客开篇语
    MySQL 整理笔记 张大哥
  • 原文地址:https://www.cnblogs.com/hanliping/p/10591698.html
Copyright © 2011-2022 走看看