首页 > 代码库 > CSV导入导出
CSV导入导出
public static DataTable ImportCSV(string strFileName, string SheetName, string[] fields) { if (strFileName == "") return null; string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Text;DATA SOURCE=" + strFileName.Replace("\\" + SheetName, ""); OleDbDataAdapter ExcelDA = new OleDbDataAdapter("select * from " + SheetName, strConn); DataTable dtCSV = new DataTable(); foreach (string field in fields) { dtCSV.Columns.Add(field, typeof(string)); } ExcelDA.Fill(dtCSV); foreach (DataColumn column in dtCSV.Columns) { column.ColumnName = column.ColumnName.Trim(); } return dtCSV; }
public static string GenerateCSVReportContent(DataTable dataSource) { StringBuilder result = new StringBuilder(); using (System.IO.StringWriter sw = new System.IO.StringWriter(result)) { StringBuilder columns = new StringBuilder(); for (int i = 0; i < dataSource.Columns.Count; i++) { if (i == 0) { columns.Append(dataSource.Columns[i].ColumnName); } else { columns.Append("," + dataSource.Columns[i].ColumnName); } } sw.WriteLine(columns.ToString()); foreach (DataRow row in dataSource.Rows) { for (int i = 0; i < dataSource.Columns.Count; i++) { if (i == 0) { sw.Write(row[i] == null ? String.Empty : "\"" + row[i].ToString().Replace("\"", "").Replace(",", "").Replace(" ", "") + "\""); } else if (i == dataSource.Columns.Count - 1) { sw.Write(","); sw.WriteLine(row[i] == null ? String.Empty : "\"" + row[i].ToString().Replace("\"", "").Replace(",", "").Replace(" ", "") + "\""); } else { sw.Write(","); sw.Write(row[i] == null ? String.Empty : "\"" + row[i].ToString().Replace("\"", "").Replace(",", "").Replace(" ", "") + "\""); } } sw.Flush(); } } return result.ToString(); }
public static string GenerateCSVReportContent(DataTable dataSource) { StringBuilder result = new StringBuilder(); using (System.IO.StringWriter sw = new System.IO.StringWriter(result)) { StringBuilder columns = new StringBuilder(); for (int i = 0; i < dataSource.Columns.Count; i++) { if (i == 0) { columns.Append(dataSource.Columns[i].ColumnName); } else { columns.Append("," + dataSource.Columns[i].ColumnName); } } sw.WriteLine(columns.ToString()); foreach (DataRow row in dataSource.Rows) { for (int i = 0; i < dataSource.Columns.Count; i++) { if (i == 0) { sw.Write(row[i] == null ? String.Empty : "\"" + row[i].ToString().Replace("\"", "").Replace(",", "").Replace(" ", "") + "\""); } else if (i == dataSource.Columns.Count - 1) { sw.Write(","); sw.WriteLine(row[i] == null ? String.Empty : "\"" + row[i].ToString().Replace("\"", "").Replace(",", "").Replace(" ", "") + "\""); } else { sw.Write(","); sw.Write(row[i] == null ? String.Empty : "\"" + row[i].ToString().Replace("\"", "").Replace(",", "").Replace(" ", "") + "\""); } } sw.Flush(); } } return result.ToString(); }
CSV导入导出
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。