我有一個方法返回一個csv行。不過,我想把它轉換成數據表。意思是,無論哪裏是「,」我想把數據放到一個新的列單元格中。將CSV轉換爲數據表
private static string ConvertGridViewRowToCsvRow(GridViewRow row)
{
StringBuilder csvRow = new StringBuilder();
bool firstCell = true;
foreach (DataControlFieldCell cell in row.Cells)
{
string text = string.Empty;
if (!String.IsNullOrEmpty(cell.Text))
{
text = cell.Text;
}
else if (cell.Controls.Count > 0)
{
foreach (var control in cell.Controls)
{
if (control is ITextControl)
{
var textControl = control as ITextControl;
text += HttpUtility.HtmlDecode(textControl.Text).Replace("\r", string.Empty).Replace("\n", string.Empty).Trim();
}
else if (control is TextImage)
{
var textImage = control as TextImage;
text += HttpUtility.HtmlDecode(textImage.Text).Replace("\r", string.Empty).Replace("\n", string.Empty).Trim();
}
}
}
if (!firstCell)
{
csvRow.Append(",");
}
csvRow.Append(MakeTextCsvFriendly(text));
firstCell = false;
}
return csvRow.ToString();
}
這是點擊一個按鈕調用ConvertGridViewRowToCsvRow
public static void Export(string fileName, GridView gv, HashSet<string> selectedRows)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "text/csv";
//SetHiddenColumnsVisibility(gv); enable if you want only selected columns to visible on export (not current business requirement)
var csvFile = new StringBuilder();
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
bool firstCell = true;
foreach (DataControlFieldHeaderCell cell in gv.HeaderRow.Cells)
{
if (!firstCell)
{
csvFile.Append(",");
}
string text = cell.ContainingField.HeaderText;
csvFile.Append(MakeTextCsvFriendly(text));
firstCell = false;
}
csvFile.Append("\r\n");
}
if (selectedRows.Count > 0)
{
foreach (GridViewRow row in gv.Rows)
{
if (row.RowType == DataControlRowType.DataRow && selectedRows.Contains(gv.DataKeys[row.RowIndex].Value.ToString()))
{
GridViewExportUtil.PrepareControlForExport(row);
csvFile.AppendLine(ConvertGridViewRowToCsvRow(row));
}
}
}
else
{
foreach (GridViewRow row in gv.Rows)
{
GridViewExportUtil.PrepareControlForExport(row);
csvFile.AppendLine(ConvertGridViewRowToCsvRow(row));
}
}
// render the htmlwriter into the response
HttpContext.Current.Response.Write(csvFile.ToString());
HttpContext.Current.Response.End();
}
}
}
我想的方法的過程中調用的方法,以取代csvFile.Append(",");
或可能一個會使用這樣一個文件來存儲數據表中的數據。
但是我需要指導構建這種方法。
[FileHelpers(http://www.filehelpers.net/)是所有你需要 –