///
/// 1 变为CSV文件流
/// 2 zip压缩
///
///
///
private byte[] ToCSVFileStream(DataTable ds, Dictionary dic)
{
//替换中文列头名称
ds = DataTableColumeName_en2ch(ds, dic);
//DataTable -> CSV data
byte[] data = ExportDataToCSVStream(ds);
//处理完毕,删除并清理缓存
ds = null;
GC.Collect();
//zip
byte[] zipData = CSharpZiper.ZipData(data, 6);
return zipData;
}
#region DataTalbe -> CSV
///
/// 导出CSV格式[文件流]
///
///
///
private byte[] ExportDataToCSVStream(DataTable dataTable)
{
if (dataTable == null || dataTable.Columns.Count == 0 || dataTable.Rows.Count == 0)
{
return null;
}
StreamEx writer = new StreamEx(true);
string column = string.Empty;
column = CreateColumn(dataTable);
writer.Write.Write(1); //1 head
writer.WriteString(column);
string line = string.Empty;
writer.Write.Write(dataTable.Rows.Count); //row Count
foreach (DataRow row in dataTable.Rows)
{
line = CreateLine(row);
writer.WriteString(line);
}
return writer.MemoryStreamBuffer;
}
private string CreateLine(DataRow row)
{
int count = m_List.Count;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++)
{
MetaItem item = m_List[i];
if (item == null || !item.ShowFlag || item.Name.ToLower().Trim() == "customcolumn_number")
{
continue;
}
int index = mapping[item.Name];
object text = index == -1 ? DBNull.Value : row[item.Name];
if (item != null)
{
if (!item.ShowFlag)
continue;
else if (!(text is DBNull) && !string.IsNullOrEmpty(item.ShowFormat))
{
switch (item.DataType)
{
case DataType.eInteger:
text = ((int)text).ToString(item.ShowFormat);
break;
case DataType.eLong:
text = ((long)text).ToString(item.ShowFormat);
break;
case DataType.eDouble:
text = ((double)text).ToString(item.ShowFormat);
break;
case DataType.eDateTime:
text = ((DateTime)text).ToString(item.ShowFormat);
break;
}
}
}
if (i == count - 1)
{
sb.AppendFormat("{0}", text);
}
else
{
sb.AppendFormat("{0}{1}", text, SplitChar[0]);
}
}
return sb.ToString();
}
Dictionary
mapping = new Dictionary();
private string CreateColumn(DataTable dataTable)
{
mapping = new Dictionary();
int count = m_List.Count;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++)
{
MetaItem item = m_List[i];
if (item == null || !item.ShowFlag || item.Name.ToLower().Trim() == "customcolumn_number")
{
continue;
}
mapping[item.Name] = GetColumeNameIndex(dataTable, item.Name);
string text = item.Text;
if (i == count - 1)
{
sb.AppendFormat("{0}", text);
}
else
{
sb.AppendFormat("{0}{1}", text, SplitChar[0]);
}
}
return sb.ToString();
}
private int GetColumeNameIndex(DataTable dataTable, string columanName)
{
columanName = columanName.ToLower().Trim();
for (int i = 0; i < dataTable.Columns.Count; i++)
{
DataColumn col = dataTable.Columns[i];
if (col.ColumnName.ToLower().Trim() == columanName)
{
return i;
}
}
return -1;
}
private char[] SplitChar
{
get
{
return new char[] { '\t' };
}
}
#endregion