私はcsv行を返すメソッドを持っています。しかし、私はこれをデータテーブルに変換したい。意味は、どこにでもある "、"私は新しい列セルにデータを入れたい。CSVをDatatableに変換する
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();
}
これは私がcsvFile.Append(",");
を交換するか、おそらく保存するために、このようなファイルを使用し1うの方法を考えていた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();
}
}
}
を呼び出すボタンクリック時に呼び出されるメソッドですDataTableのデータ
しかし、私はこのメソッドを構造化する際の指針が必要です。
は[FileHelpers](http://www.filehelpers.net/)それが仕事の罰金だ場合は、答えとしてそれをマークすることを忘れないでください、 –