を発生させるExcelファイルASP.NET [定休日]
-
02-07-2019 - |
質問
私は約を追加する部へASP.NET アプリケーションソフVB.NET codebehind)をユーザに返されるデータとしてExcelファイルを生成しますに基づくデータベースのデータです。あはいくつかの方法が考えられていて、それぞれ独自の問題点がありました。どのよう す のデータはもらえますか?を探しているものとして素直なことです。
解決
CSV
長所:
- シンプル
短所:
- 他のロケールまたは異なるExcel構成(つまり、リスト区切り記号)では機能しない場合があります
- フォーマット、数式などを適用できません
HTML
長所:
- さらにシンプル
- 単純な書式設定と数式をサポート
短所:
- xlsとしてファイルに名前を付ける必要があり、Excelは非ネイティブのExcelファイルを開くことについて警告する場合があります
- ワークブックごとに1つのワークシート
OpenXML(Office 2007 .XLSX)
長所:
- ネイティブExcel形式
- すべてのExcel機能をサポート
- Excelのインストールコピーを必要としない
- ピボットテーブルを生成できます
- オープンソースプロジェクト EPPlus を使用して生成できます
短所:
- Excel 2007以外での互換性の制限(最近は問題になりません)
- サードパーティのコンポーネントを使用していない限り複雑です
SpreadSheetML(オープンフォーマットXML)
長所:
- ネイティブのExcel形式と比較した単純な
- Excelのほとんどの機能をサポート:書式設定、スタイル、数式、ワークブックごとの複数シート
- Excelを使用するためにExcelをインストールする必要はありません
- サードパーティのライブラリは必要ありません-XMLを書き出すだけです
- Excel XP / 2003/2007でドキュメントを開くことができます
短所:
- 優れたドキュメントの欠如
- Excelの古いバージョン(2000年以前)ではサポートされていません
- 書き込み専用。一度開くとExcelから変更を加えると、ネイティブExcelに変換されます。
XLS(サードパーティコンポーネントによって生成された)
長所:
- すべての書式設定、式などを含むネイティブExcelファイルを生成します
短所:
- 費用
- 依存関係を追加
COM相互運用
長所:
- ネイティブのMicrosoftライブラリを使用
- ネイティブドキュメントのサポートを読む
短所:
- 非常に遅い
- 依存関係/バージョンの一致の問題
- 読み取り時のWeb使用の同時実行性/データ整合性の問題
- 非常に遅い
- Web使用のスケーリングの問題(同時実行性とは異なる):サーバー上に重いExcelアプリのインスタンスを多数作成する必要がある
- Windowsが必要
- 遅いと言いましたか?
他のヒント
データをhtmlテーブルセルとして出力し、 .xls
または .xlsx
拡張子を貼り付けると、Excelはネイティブドキュメントのように開きます。この方法で制限された書式設定や式の計算を行うこともできるため、CSVよりもはるかに強力です。また、htmlテーブルの出力は、ASP.NetなどのWebプラットフォームから非常に簡単に実行できるはずです;)
Excelワークブック内に複数のワークシートまたは名前付きワークシートが必要な場合、 SpreadSheetML
というXMLスキーマを介して同様のことができます。これは、Office 2007に同梱された新しい形式ではありませんが 、Excel 2000にまでさかのぼって完全に異なるものです。その仕組みを説明する最も簡単な方法は、例です:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author>Your_name_here</Author>
<LastAuthor>Your_name_here</LastAuthor>
<Created>20080625</Created>
<Company>ABC Inc</Company>
<Version>10.2625</Version>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>6135</WindowHeight>
<WindowWidth>8445</WindowWidth>
<WindowTopX>240</WindowTopX>
<WindowTopY>120</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom" />
<Borders />
<Font />
<Interior />
<NumberFormat />
<Protection />
</Style>
</Styles>
<Worksheet ss:Name="Sample Sheet 1">
<Table ss:ExpandedColumnCount="2" x:FullColumns="1" x:FullRows="1" ID="Table1">
<Column ss:Width="150" />
<Column ss:Width="200" />
<Row>
<Cell><Data ss:Type="Number">1</Data></Cell>
<Cell><Data ss:Type="Number">2</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">3</Data></Cell>
<Cell><Data ss:Type="Number">4</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">5</Data></Cell>
<Cell><Data ss:Type="Number">6</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">7</Data></Cell>
<Cell><Data ss:Type="Number">8</Data></Cell>
</Row>
</Table>
</Worksheet>
<Worksheet ss:Name="Sample Sheet 2">
<Table ss:ExpandedColumnCount="2" x:FullColumns="1" x:FullRows="1" ID="Table2">
<Column ss:Width="150" />
<Column ss:Width="200" />
<Row>
<Cell><Data ss:Type="String">A</Data></Cell>
<Cell><Data ss:Type="String">B</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">C</Data></Cell>
<Cell><Data ss:Type="String">D</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">E</Data></Cell>
<Cell><Data ss:Type="String">F</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">G</Data></Cell>
<Cell><Data ss:Type="String">H</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook>
DataTable からの場合:
public static void DataTabletoXLS(DataTable DT, string fileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-16";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
string tab = "";
foreach (DataColumn dc in DT.Columns)
{
HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in DT.Rows)
{
tab = "";
for (i = 0; i < DT.Columns.Count; i++)
{
HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
Gridview から:
public static void GridviewtoXLS(GridView gv, string fileName)
{
int DirtyBit = 0;
int PageSize = 0;
if (gv.AllowPaging == true)
{
DirtyBit = 1;
PageSize = gv.PageSize;
gv.AllowPaging = false;
gv.DataBind();
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
Utilities.Export.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
Utilities.Export.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
Utilities.Export.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString().Replace("£", ""));
HttpContext.Current.Response.End();
}
if (DirtyBit == 1)
{
gv.PageSize = PageSize;
gv.AllowPaging = true;
gv.DataBind();
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
Utilities.Export.PrepareControlForExport(current);
}
}
}
これは、SpreadMLの無料のラッパーです。非常に効果的です。
ご回答に基づき、協議の仲間で、最善の解決策を生み出すには、XMLファイルのHTMLテーブルを押しして取り付けます。を変更する私のすることができるのが、このデータ(HTMLのテーブル)で書き込まれる直接のレスポンスオブジェクト、これを削除する必要がありファイルを、面倒によるアクセス権問題、I/O争が正確ではないことを予定パージが発生します。
このスニペットのコー---いことを確認されていると思いますが、まだ供給すべてのコードはないと思い、考えます。
Dim uiTable As HtmlTable = GetUiTable(groupedSumData)
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", String.Format("inline; filename=OSSummery{0:ddmmssf}.xls", DateTime.Now))
Dim writer As New System.IO.StringWriter()
Dim htmlWriter As New HtmlTextWriter(writer)
uiTable.RenderControl(htmlWriter)
Response.Write(writer.ToString)
Response.End()
ExcelはHTMLを理解しているため、データをHTMLテーブルとして.xls拡張子を持つ一時ファイルに書き出すだけで、ファイルのFileInfoを取得し、使用してブローバックできます
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fi.FullName);
Response.End();
一時ファイルを避けたい場合は、WriteFileを使用する代わりに、メモリ内ストリームに書き込み、バイトを書き戻すことができます
content-lengthヘッダーが省略されている場合、htmlを直接書き戻すことができますが、これはすべてのブラウザーで常に正しく機能しない場合があります
個人的にはXMLメソッドを好みます。データセットのデータベースからデータを返し、XMlに保存してから、適切なドキュメントをフォーマットする変換ルールを含むxsltファイルを作成し、単純なXML変換でジョブを完了します。これについての最も良い部分は、セルの書式設定、条件付き書式設定、ヘッダーとフッターの設定、および印刷範囲の設定です。
これを数回行いましたが、そのたびに最も簡単な方法は、単純にCSV(カンマ区切り値)ファイルを返すことでした。 Excelは完全にインポートし、実行は比較的高速です。
常に優れたデータグリッドからデータをエクスポートします。 HTMLに変換してからExcelファイルに書き込む
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Response.AddHeader("content-disposition", "fileattachment;filename=YOURFILENAME.xls")
Me.EnableViewState = False
Dim sw As System.IO.StringWriter = New System.IO.StringWriter
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
ClearControls(grid)
grid.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
このメソッドの唯一の落とし穴は、多くのグリッドにボタンまたはリンクが含まれていたため、これも必要なことです:
'needed to export grid to excel to remove link button control and represent as text
Private Sub ClearControls(ByVal control As Control)
Dim i As Integer
For i = control.Controls.Count - 1 To 0 Step -1
ClearControls(control.Controls(i))
Next i
If TypeOf control Is System.Web.UI.WebControls.Image Then
control.Parent.Controls.Remove(control)
End If
If (Not TypeOf control Is TableCell) Then
If Not (control.GetType().GetProperty("SelectedItem") Is Nothing) Then
Dim literal As New LiteralControl
control.Parent.Controls.Add(literal)
Try
literal.Text = CStr(control.GetType().GetProperty("SelectedItem").GetValue(control, Nothing))
Catch
End Try
control.Parent.Controls.Remove(control)
Else
If Not (control.GetType().GetProperty("Text") Is Nothing) Then
Dim literal As New LiteralControl
control.Parent.Controls.Add(literal)
literal.Text = CStr(control.GetType().GetProperty("Text").GetValue(control, Nothing))
control.Parent.Controls.Remove(control)
End If
End If
End If
Return
End Sub
どこかでうまくいくことがわかりました。
OpenXMLに基づく無料のオープンソースExcel生成ライブラリをお勧めします
数ヶ月前に助けてくれました。
これは、ストアドプロシージャから取得したレポートです。結果はExcelにエクスポートされます。 ADO.NETの代わりにADOを使用し、その理由はこの行です
oSheet.Cells(2, 1).copyfromrecordset(rst1)
ほとんどの作業を行い、ado.netでは利用できません。
‘Calls stored proc in SQL Server 2000 and puts data in Excel and ‘formats it
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As ADODB.Connection
cnn = New ADODB.Connection
cnn.Open("Provider=SQLOLEDB;data source=xxxxxxx;" & _
"database=xxxxxxxx;Trusted_Connection=yes;")
Dim cmd As New ADODB.Command
cmd.ActiveConnection = cnn
cmd.CommandText = "[sp_TomTepley]"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
cmd.CommandTimeout = 0
cmd.Parameters.Refresh()
Dim rst1 As ADODB.Recordset
rst1 = New ADODB.Recordset
rst1.Open(cmd)
Dim oXL As New Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
'oXL = CreateObject("excel.application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
Dim Column As Integer
Column = 1
Dim fld As ADODB.Field
For Each fld In rst1.Fields
oXL.Workbooks(1).Worksheets(1).Cells(1, Column).Value = fld.Name
oXL.Workbooks(1).Worksheets(1).cells(1, Column).Interior.ColorIndex = 15
Column = Column + 1
Next fld
oXL.Workbooks(1).Worksheets(1).name = "Tom Tepley Report"
oSheet.Cells(2, 1).copyfromrecordset(rst1)
oXL.Workbooks(1).Worksheets(1).Cells.EntireColumn.AutoFit()
oXL.Visible = True
oXL.UserControl = True
rst1 = Nothing
cnn.Close()
Beep()
End Sub
GridViewにデータを入力すると、この関数を使用してHTML形式のデータを取得できますが、ブラウザにはExcelファイルであることを示します。
Public Sub ExportToExcel(ByVal fileName As String, ByVal gv As GridView)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
HttpContext.Current.Response.ContentType = "application/ms-excel"
Dim sw As StringWriter = New StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
Dim table As Table = New Table
table.GridLines = gv.GridLines
If (Not (gv.HeaderRow) Is Nothing) Then
PrepareControlForExport(gv.HeaderRow)
table.Rows.Add(gv.HeaderRow)
End If
For Each row As GridViewRow In gv.Rows
PrepareControlForExport(row)
table.Rows.Add(row)
Next
If (Not (gv.FooterRow) Is Nothing) Then
PrepareControlForExport(gv.FooterRow)
table.Rows.Add(gv.FooterRow)
End If
table.RenderControl(htw)
HttpContext.Current.Response.Write(sw.ToString)
HttpContext.Current.Response.End()
End Sub
Private Sub PrepareControlForExport(ByVal control As Control)
Dim i As Integer = 0
Do While (i < control.Controls.Count)
Dim current As Control = control.Controls(i)
If (TypeOf current Is LinkButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
ElseIf (TypeOf current Is ImageButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
ElseIf (TypeOf current Is HyperLink) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
ElseIf (TypeOf current Is DropDownList) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
ElseIf (TypeOf current Is CheckBox) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
End If
If current.HasControls Then
PrepareControlForExport(current)
End If
i = i + 1
Loop
End Sub
Microsoft.Office.Interop名前空間を介したCOM相互運用は避けてください。とても遅くて、信頼できず、スケーラブルではありません。マゾには適用されません。
このライブラリを使用すると、 http://officehelper.codeplex.com/を使用して、適切にフォーマットされたExcelファイルを簡単に作成できます。ドキュメント。
WebサーバーにMicrosoft Officeをインストールする必要はありません!
CSVが最も簡単な方法です。ほとんどの場合、Excelにリンクされています。それ以外の場合は、オートメーションAPIまたはXML形式を使用する必要があります。 APIとXMLの使用はそれほど難しくありません。
CSVルート(上記のとおり)を使用するか、最近ではより頻繁にInfragistics NetAdvantageを使用してファイルを生成しています。 (Infragisticsが使用されているほとんどの場合、既存のUltraWebGridをエクスポートするだけです。これは、追加のフォーマット調整が必要でない限り、本質的に1 LOCソリューションです。Excel/ BIFFファイルも手動で生成できます。必要になることはめったにありません。)
man、.netでそれを行うことができるコンポーネントがあると思いますが、古典的なASPでは、すでにHTMLテーブルを作成し、ページのMIMEタイプをvnd / msexcelに変更しました。 gridviewはhtmlテーブルであるため、gridviewを使用してMIMEタイプを変更すると動作するはずです。
&quot;これらの数字はテキストとして保存されているようです&quot;緑の三角形は、Open XML形式を使用することです。避けられない緑色の三角形を避けるために、それを使用する価値があります。
Excelレポートで見た最善の方法は、XML拡張を使用してXMLでデータを書き出し、正しいコンテンツタイプでクライアントにストリーミングすることです。 (application / xls)
これは、基本的な書式設定が必要なレポートで機能し、テキスト比較ツールを使用して既存のスプレッドシートと比較できます。
これがイントラネット用であり、アクセス許可を設定しIEを命令できる場合、 Excelを駆動するJScript / VBScript 。これにより、サーバーでExcelを自動化する手間をかけずに、ネイティブのExcel書式設定が可能になります。
かなりニッチなシナリオを除き、このアプローチを本当に推奨するかどうかはわかりませんが、古典的なASPの全盛期にはかなり一般的でした。
もちろん、サードパーティのコンポーネントをいつでも使用できます。個人的には、Spire.XLS http://www.e-で良い経験をしました。 iceblue.com/xls/xlsintro.htm
コンポーネントはアプリケーション内で非常に簡単に使用できます:
Workbook workbook = new Workbook();
//Load workbook from disk.
workbook.LoadFromFile(@"Data\EditSheetSample.xls");
//Initailize worksheet
Worksheet sheet = workbook.Worksheets[0];
//Writes string
sheet.Range["B1"].Text = "Hello,World!";
//Writes number
sheet.Range["B2"].NumberValue = 1234.5678;
//Writes date
sheet.Range["B3"].DateTimeValue = System.DateTime.Now;
//Writes formula
sheet.Range["B4"].Formula = "=1111*11111";
workbook.SaveToFile("Sample.xls");
この回答は、コンテンツを添付ファイルとしてプッシュする場合(ms以外のブラウザで最もクリーンなソリューションであることがわかった)、次に、Excel 2000-2003で開きます。そのタイプは「Excel Webページ」です。ネイティブのExcelドキュメントではありません。
次に、「タイプとして保存」の使用方法をユーザーに説明する必要があります。 Excel内からExcelドキュメントに変換します。ユーザーがこのドキュメントを編集してからサイトに再アップロードする必要がある場合、これは苦痛です。
CSVを使用することをお勧めします。簡単で、ユーザーがExcel内から開く場合、Excelは少なくともネイティブ形式で保存するように求めます。
データに基づいてCSVファイルを作成するだけです。なぜなら、それが最もクリーンであり、Excelがそれを適切にサポートしているからです。ただし、より柔軟な形式が必要な場合は、実際のExcelファイルを生成するためのサードパーティツールがいくつかあるはずです。
これは、データテーブルをCSVとしてストリーム配信するソリューションです。速く、きれいで、簡単で、入力のコンマを処理します。
public static void ExportToExcel(DataTable data, HttpResponse response, string fileName)
{
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.ContentType = "text/csv";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
for (int i = 0; i < data.Columns.Count; i++)
{
response.Write(data.Columns[i].ColumnName);
response.Write(i == data.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < data.Columns.Count; i++)
{
response.Write(String.Format("\"{0}\"", row[i].ToString()));
response.Write(i == data.Columns.Count - 1 ? "\n" : ",");
}
}
response.End();
}
WebフォームC#からエクスポートする関数を作成し、他のユーザーに役立つことを期待しています
public void ExportFileFromSPData(string filename, DataTable dt)
{
HttpResponse response = HttpContext.Current.Response;
//clean up the response.object
response.Clear();
response.Buffer = true;
response.Charset = "";
// set the response mime type for html so you can see what are you printing
//response.ContentType = "text/html";
//response.AddHeader("Content-Disposition", "attachment;filename=test.html");
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.ContentEncoding = System.Text.Encoding.UTF8;
response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
//style to format numbers to string
string style = @"<style> .text { mso-number-format:\@; } </style>";
response.Write(style);
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
GridView dg = new GridView();
dg.DataSource = dt;
dg.DataBind();
foreach (GridViewRow datarow in dg.Rows)
{
//format specific cell to be text
//to avoid 1.232323+E29 to get 1232312312312312124124
datarow.Cells[0].Attributes.Add("class", "text");
}
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
CSVファイルの代わりにExcelを使用する必要がある場合は、サーバーのExcelインスタンスでOLEオートメーションを使用する必要があります。これを行う最も簡単な方法は、テンプレートファイルを用意し、プログラムでデータを入力することです。別のファイルに保存します。
ヒント:
- インタラクティブに実行しないでください。ユーザーにプロセスを開始してから、ファイルへのリンクを含むページを投稿してもらいます。これにより、スプレッドシートの生成中に潜在的なパフォーマンスの問題が軽減されます。
- 前述のテンプレートを使用します。変更が簡単になります。
- Excelがダイアログをポップアップしないように設定されていることを確認してください。 Webサーバーでは、これによりExcelインスタンス全体がハングします。
- Excelインスタンスを別のサーバー、できればファイアウォールの背後に保管し、潜在的なセキュリティホールとして公開されないようにします。
- リソースの使用状況に注意してください。 OLEオートメーションインターフェイス上でスプレッドシートを生成する(PIAはこれを単なるシムにしています)は、かなり重いプロセスです。これを大量のデータに拡張する必要がある場合は、アーキテクチャを多少賢くする必要があります。
ファイルの形式が少し基本的であることを気にしない場合、「MIMEタイプを使用してHTMLテーブルを開くのに優れた方法」アプローチの一部が機能します。これらのアプローチは、クライアントへのCPUの負荷を軽減します。スプレッドシートの形式をきめ細かく制御したい場合は、おそらく上記のようにExcel自体を使用してファイルを生成する必要があります。