可導出CSV格式文件,用Excel打開;
/// <summary>
/// CSV格式化
/// </summary>
/// <param name="data">數據</param>
/// <returns>格式化數據</returns>
private static string FormatCsvField(string data)
{
return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
}
/// <summary>
/// 獲取DataGrid數據,返回StringBuilder類型數據,用以生成CSV格式數據
/// </summary>
/// <param name="withHeaders">是否需要表頭</param>
/// <param name="grid">DataGrid</param>
/// <returns>Excel內容字符串</returns>
private static string GetGridData(bool withHeaders, DataGrid grid)
{
System.Reflection.PropertyInfo propInfo;
System.Windows.Data.Binding binding;
var strBuilder = new System.Text.StringBuilder();
var source = grid.ItemsSource;
if (source == null) return "";
var headers = new List<string>();
try
{
if (grid.Columns.Count == 0)
{
return null;
}
grid.Columns.ToList().ForEach(col =>
{
if (col is DataGridBoundColumn)
{
headers.Add(FormatCsvField(col.Header.ToString()));
}
});
strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
foreach (Object data in source)
{
var csvRow = new List<string>();
foreach (DataGridColumn col in grid.Columns)
{
if (col is DataGridBoundColumn)
{
binding = (col as DataGridBoundColumn).Binding;
string colPath = binding.Path.Path;
propInfo = data.GetType().GetProperty(colPath);
if (propInfo != null)
{
csvRow.Add(FormatCsvField(propInfo.GetValue(data, null).ToString()));
}
}
}
strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
}
return strBuilder.ToString();
}
catch { return null; }
}
/// <summary>
/// 導出Excel
/// </summary>
public void ExportGridToExcel()
{
try
{
string data = GetGridData(true, StatisticsDetail);
if (string.IsNullOrEmpty(data))
return;
SaveFileDialog sfd = new SaveFileDialog
{
DefaultExt = "csv",
Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
FilterIndex = 1
};
if (sfd.ShowDialog() == true)
{
using (Stream stream = sfd.OpenFile())
{
using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
{
data = data.Replace(",", "\t");
writer.Write(data);
writer.Close();
}
stream.Close();
MessageBox.Show("導出成功!");
}
}
}
catch { }
}