グリッドビューデータをエクスポートする
-
05-07-2019 - |
質問
グリッドビューを Excel スプレッドシートにエクスポートする最良の方法は何ですか? これは簡単そう
ただし、私の Gridview にはエクスポート属性がありません。これを行う最も早い方法は何ですか?
解決
ExcelへのエクスポートでbtnexporttoExcel Clickイベントでこのコードを記述します。
string attachment = "attachment; filename=Export.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(htw);
//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
他のヒント
おそらくこれには何かがありますが、自分でやりたい場合は、GridView.Rowsコレクションを調べ、その中のGridViewRow.Cellsコレクションを歩くコードを書くことができます。
そこからCSVファイルを作成するのは非常に簡単であるはずであり、Excelは問題なく読み取ることができます。
CSVファイルは、引用符で囲まれた値を持つコンマで区切られた単なるテキストファイルです。このように:
"value", "value", "value"
"value", "value", "value"
メモ帳を開いて手動で作成し、試してみることができます。
これを数回行いました。 ExcelにはXMLバージョンがあります。拡張子は.xmlになりますが、ファイルの拡張子を.xlsに変更するだけで、XML形式のファイルがExcelで正常に開きます。
このアプローチの最大のハードルは、Excel XML形式です。私は通常、私が望むおおよその形式でExcelでExcelファイルを作成します。次に、ExcelファイルをXML形式で保存し、テキストエディターで開きます。
通常、このExcelサンプルページからテンプレートファイルを作成します。次に、Gridviewで情報をエクスポートするときに、作成する予定のセルを含むセクションのxmlを作成するだけで、テンプレートファイルに既にテキストを追加して追加するだけです。
xml形式のExcelファイルを開くと、必要なXMLを比較的簡単に把握できます。理解するのが最も難しい部分は、セルがXMLファイルの上部にあるフォーマットオプションを参照する方法です。
幸運なことに、さらに説明が必要な場合はお知らせください。
編集: 生成する必要のある必要なxmlの感触をつかむために、テンプレートExcelファイルを作成する必要があるのは1回だけです。 xmlを生成したら、次のコードを使用してそれをユーザーに送信します。
string fileName = "ExportedFile.xls";
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
ExportToExcel(HttpContext.Current.Response.OutputStream, testUID);
Response.End();
public static void ExportToExcel(Stream outputStream)
{
XmlTextWriter xmlSink = new XmlTextWriter(outputStream, Encoding.Default);
//ExcelHeaderString and ExcelStylesString are from the template
xmlSink.WriteRaw(ExcelHeaderString);
xmlSink.WriteRaw(ExcelStylesString);
//write your elements here
xmlSink.WriteElement("YourElements");
//ExcelFooterString is from the template
xmlSink.WriteRaw(ExcelFooterString);
}
.netのこのライブラリは、私たちのユースケースで非常にうまく機能しています。
このライブラリを使用すると、XMLを使用してExcelワークブックを生成できます。C#で100%ビルドされ、ファイルを生成するためにExcelをインストールする必要はありません。シンプルなオブジェクトモデルを公開して、XMLワークブックを生成します。
GridViewコントロールとの組み込みの統合はありませんが、汎用アダプターの作成は簡単で、他のプロジェクトで再利用できます。
この方法は、XMLをサーバーにインストールしたり、XMLを使用したりすることなく、Excel形式に直接移行します。
Protected Sub ExportToExcel()
Dim gv1 As GridView = FindControlRecursive(objPlaceHolder, "GridView1")
If Not gv1 Is Nothing Then
Response.ClearHeaders()
Response.ClearContent()
' Set the content type to Excel
Response.ContentType = "application/vnd.ms-excel"
' make it open the save as dialog
Response.AddHeader("content-disposition", "attachment; filename=ExcelExport.xls")
'Turn off the view state
Me.EnableViewState = False
'Remove the charset from the Content-Type header
Response.Charset = String.Empty
Dim myTextWriter As New System.IO.StringWriter
Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter)
Dim frm As HtmlForm = New HtmlForm()
Controls.Add(frm)
frm.Controls.Add(gv1)
'Get the HTML for the control
frm.RenderControl(myHtmlTextWriter)
'Write the HTML to the browser
Response.Write(myTextWriter.ToString())
'End the response
Response.End()
End If
End Sub
Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
If root.ID = id Then
Return root
End If
Dim c As Control
For Each c In root.Controls
Dim t As Control = FindControlRecursive(c, id)
If Not t Is Nothing Then
Return t
End If
Next
Return Nothing
End Function
私が使用した CarlosAg.ExcelXmlWriter
リンク.
全部ループしてみた GridViews
HeaderCells
そしてすべての行を通過します。唯一のことは、ページングを許可し、複数のページがある場合は、PageSize を高い値 (私は 10000000 に設定) に設定する必要があるということです。 DataBind
の GridView
もう一度、仕事をしてください。その後、古い PageSize 値を元に戻します。誰かがより良い解決策を知っていれば、大歓迎です。
編集:try/catch が存在するのは、何らかの理由でコントロールの型をチェックしてから Label またはにキャストすることができないためです。 LinkButton ==> control.GetType()
.
これが私のコードです。
public static Workbook CreateWorkbook(GridView gridView)
{
int pageSize = gridView.PageSize;
gridView.PageSize = 10000000;
gridView.DataBind();
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets.Add("Export");
WorksheetStyle style = workbook.Styles.Add("headerStyle");
style.Font.Bold = true;
style = workbook.Styles.Add("defaultStyle");
style.Alignment.WrapText = true;
style = workbook.Styles.Add("infoStyle");
style.Font.Color = "Red";
style.Font.Bold = true;
sheet.Table.Rows.Add(new WorksheetRow());
WorksheetRow headerRow = new WorksheetRow();
foreach (DataControlFieldHeaderCell cell in gridView.HeaderRow.Cells)
{
if (!string.IsNullOrEmpty(cell.Text))
headerRow.Cells.Add(cell.Text, DataType.String, "headerStyle");
else
foreach (Control control in cell.Controls)
{
LinkButton linkButton = new LinkButton();
try
{
linkButton = (LinkButton)control;
}
catch { }
if (!string.IsNullOrEmpty(linkButton.Text))
headerRow.Cells.Add(linkButton.Text, DataType.String, "headerStyle");
else
{
Label label = new Label();
try
{
label = (Label)control;
}
catch { }
if (!string.IsNullOrEmpty(label.Text))
headerRow.Cells.Add(label.Text, DataType.String, "headerStyle");
}
}
}
sheet.Table.Rows.Add(headerRow);
foreach (GridViewRow row in gridView.Rows)
{
WorksheetRow wrow = new WorksheetRow();
foreach (TableCell cell in row.Cells)
{
foreach (Control control in cell.Controls)
{
if (control.GetType() == typeof(Label))
{
wrow.Cells.Add(((Label)control).Text, DataType.String, "defaultStyle");
}
}
}
sheet.Table.Rows.Add(wrow);
}
gridView.PageSize = pageSize;
return workbook;
}
Private exportToExcel As Boolean = False
Private Sub LoadInExcel()
Me.Response.ClearContent()
Me.Response.AddHeader("content-disposition", "attachment; filename=MyFile.xls")
Me.Response.ContentType = "application/ms-excel"
Dim sw1 As New IO.StringWriter
Dim htw1 As HtmlTextWriter = New HtmlTextWriter(sw1)
GridView1.RenderControl(htw1)
Response.Write(sw1.ToString())
Response.End()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Confirms that an HtmlForm control is rendered for the specified ASP.NET
' server control at run time.
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
If exportToExcel Then
LoadInExcel()
End If
MyBase.Render(writer)
End Sub
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
exportToExcel = True
End Sub
Excelをインストールし、プロジェクトのOffice相互運用ライブラリを参照する必要があります。 追加:
Microsoft.Office.Coreをインポートし、 Microsoft.Office.Interopをインポートします
上記の解決策は、gridviewを取得し、htmlを引き出します。その後、Excelに書き込みます。グリッドから送信されるHTMLには、パディングなどのスタイル属性が含まれます。色。また、ソート可能な列見出しをリンクのように見せます。これを使用して、カスタムパーサーを作成し、不要なスタイリングをすべて取り除き、生データのみを取得しました。このタスクは各グリッドに固有なので、あなたに任せます。
コードが存在しない場合でも、VerifyRenderingInServerFormにオーバーライドを含めることが非常に重要です。