DevExpress.XtraGrid.GridControl有多个ExportToXXX的方法,提供多种格式的导出,极大节省了人力。如果数据集里面有bool的数据,Grid就会显示成checkbox的形式,导出成pdf、excel当然是没有问题。但导出txt和csv格式时,对应bool字段的值就会空白,没有任何数据导出。这个bug可以在XtraGrid的demo里面看到。导出数据空白的问题在官方资料中目前没有找到资料,只好自己做了。
以下是导出txt的代码,csv也是稍加修改即可实现。
代码
private void ExportGridToTxt(GridView view, string path, char spliter)
{
if (view != null)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(path, false, Encoding.Default);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < view.Columns.Count; i++)
{
sb.Append(view.Columns[i].Caption + spliter);
}
sb.AppendLine();
for (int i = 0; i < view.RowCount; i++)
{
DataRow dr = view.GetDataRow(i);
for (int j = 0; j < view.Columns.Count; j++)
{
GridColumn col = view.Columns[j];
if (col.ColumnType == typeof(bool))
{
bool val = (bool)(view.GetRowCellValue(i, col));
sb.Append((bool)val ? "Y" : "N");
}
else
{
string displayText = view.GetRowCellDisplayText(i, col);
sb.Append(displayText);
}
if (j != view.Columns.Count - 1)
{
sb.Append(spliter);
}
else
{
sb.AppendLine();
}
}
}
sw.Write(sb.ToString());
sw.Flush();
}
finally
{
if (sw != null)
{
sw.Close();
}
}
}
}
{
if (view != null)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(path, false, Encoding.Default);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < view.Columns.Count; i++)
{
sb.Append(view.Columns[i].Caption + spliter);
}
sb.AppendLine();
for (int i = 0; i < view.RowCount; i++)
{
DataRow dr = view.GetDataRow(i);
for (int j = 0; j < view.Columns.Count; j++)
{
GridColumn col = view.Columns[j];
if (col.ColumnType == typeof(bool))
{
bool val = (bool)(view.GetRowCellValue(i, col));
sb.Append((bool)val ? "Y" : "N");
}
else
{
string displayText = view.GetRowCellDisplayText(i, col);
sb.Append(displayText);
}
if (j != view.Columns.Count - 1)
{
sb.Append(spliter);
}
else
{
sb.AppendLine();
}
}
}
sw.Write(sb.ToString());
sw.Flush();
}
finally
{
if (sw != null)
{
sw.Close();
}
}
}
}
我装的版本是9.1