常用类-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()) + "\n";
                }
                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>

猜你喜欢

转载自www.cnblogs.com/hanliping/p/10591698.html