C#データインポート/エクスポートExcelファイルおよびwinFormエクスポートExeclまとめ

17027 ワード

一、asp.NetでExeclをエクスポートする方法:
asp.NetでExeclをエクスポートするには、エクスポートしたファイルをサーバのフォルダの下に保存し、ブラウザにファイルアドレスを出力する2つの方法があります.1つは、ファイル出力ストリームをブラウザに直接書き込むことです.Responseで出力する場合、tで区切られたデータは、execlをエクスポートする場合、分列に等価であり、改行に等価である.
1.html全体をexeclに出力する
この方法では、html内のすべての内容、例えばボタン、テーブル、ピクチャなどをすべてExeclに出力します.
 
  
Response.Clear();
Response.Buffer= true;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");
Response.ContentEncoding=System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
 
ここではContentTypeプロパティを利用しています.デフォルトのプロパティはtext/htmlです.この場合、スーパーテキスト、すなわち一般的なWebページのフォーマットをクライアントに出力します.ms-excelに変更すると、excelフォーマット、つまりスプレッドシートのフォーマットでクライアントに出力します.これにより、ブラウザはダウンロード保存を求めます.ContentTypeのプロパティには、image/JPEG、text/HTML;image/GIF;vnd.ms-excel/msword .同様に、画像やwordドキュメントなどを出力(エクスポート)することもできます.次の方法も、このプロパティを使用します.
2、データGridコントロールのデータをExeclにエクスポートする
上記の方法では,導出機能を実現したが,ボタン,ページングボックスなどのhtml中のすべての出力情報を同時に導いた.一般的には、データ、DataGridコントロールのデータをエクスポートします.
 
  
System.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();

DataGridがページングされている場合は、現在のページの情報、つまりDataGridに表示されている情報をエクスポートします.あなたのselect文のすべての情報ではありません.
使いやすいように、書き方は以下の通りです.
 
  
public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}

使用法:DGToExcel(datagrid 1);
3、データセットのデータをExeclにエクスポートする
以上のように,導出した情報をクライアントに出力することで,導出できると考えられる.では、DataSetのデータを書き出し、つまりDataSetのテーブルの各行の情報をms-excel形式でResponseからhttpストリームにすることでOKです.説明:パラメータdsは、execl 2006などの接尾辞名を含む、データテーブルが埋め込まれたDataSetであるべきである.xls
 
  
public void CreateExcel(DataSet ds,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename="+FileName);
string colHeaders= "", ls_item="";

// , DataSet
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select();// dt.Select("id>10")
int i=0;
int cl=dt.Columns.Count;


// , \t ,
for(i=0;i{
if(i==(cl-1))// ,

{
colHeaders +=dt.Columns[i].Caption.ToString() +"
";
}
else
{
colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
}

}
resp.Write(colHeaders);
// HTTP

//
foreach(DataRow row in myRow)
{
// HTTP , ls_item
for(i=0;i{
if(i==(cl-1))// ,

{
ls_item +=row[i].ToString()+"
";
}
else
{
ls_item+=row[i].ToString()+"\t";
}

}
resp.Write(ls_item);
ls_item="";

}
resp.End();
}

4、dataviewをexeclにエクスポートする
より変化や行列の不規則に富むexeclエクスポートを実現するには、本法を使用します.   
 
  
public void OutputExcel(DataView dv,string str)
{
//dv Excel ,str
GC.Collect();
Application excel;// = new Application();
int rowIndex=4;
int colIndex=1;

_Workbook xBk;
_Worksheet xSt;

excel= new ApplicationClass();

xBk = excel.Workbooks.Add(true);

xSt = (_Worksheet)xBk.ActiveSheet;

//
//
//
foreach(DataColumn col in dv.Table.Columns)
{
colIndex++;
excel.Cells[4,colIndex] = col.ColumnName;
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//
}

//
//
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
if(col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//
}
else
if(col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = " ";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//
//
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;// , 56
//
//
//
excel.Cells[2,2] = str;
//
//
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
//
//
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
//
//
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
//
//
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//
//
//
//
excel.Visible=true;

//xSt.Export(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls");

ds = null;
xBk.Close(false, null,null);

excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
string path = Server.MapPath(this.xlfile.Text+".xls");

System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset="GB2312";
Response.ContentEncoding=System.Text.Encoding.UTF8;
// , " / "
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// , ,
Response.AddHeader("Content-Length", file.Length.ToString());

// ,
Response.ContentType = "application/ms-excel";

//
Response.WriteFile(file.FullName);
//

Response.End();
}


上記の面では、エクスポートするexeclデータをブラウザに直接出力し、まずサーバのフォルダに保存し、クライアントにファイルを送信する方法です.これにより、エクスポートされたファイルを永続的に保存し、他の機能を実現できます.
5、execlファイルをサーバーにエクスポートし、ダウンロードします.
二、winFormでExeclをエクスポートする方法:
1、方法1:
 
  
public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[0];

sFile=url+"\\myExcel.xls";
sTemplate=url+"\\MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item(1);
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item(1);
// sheet
oSheet.Name="Sheet1";

oCells=oSheet.Cells;
// dumpdata , Excel
DumpData(dt,oCells);
//
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
// Excel, COM
oExcel.Quit();

GC.Collect();
KillProcess("Excel");
}

private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}

2、方法2:
 
  
protected void ExportExcel()
{
gridbind();

if(ds1==null) return;

string saveFileName="";
// bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel |*.xls";
saveDialog.FileName ="Sheet1";
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")<0) return; //
// excelapp.Workbooks.Open (App.path & \\ .xls)


Excel.Application xlApp=new Excel.Application();
object missing=System.Reflection.Missing.Value;


if(xlApp==null)
{
MessageBox.Show(" Excel , Excel");
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];// sheet1
Excel.Range range;


string oldCaption=Title_label .Text.Trim ();
long totalCount=ds1.Tables[0].Rows.Count;
long rowRead=0;
float percent=0;

worksheet.Cells[1,1]=Title_label .Text.Trim ();
//
for(int i=0;i{
worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName;
range=(Excel.Range)worksheet.Cells[2,i+1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;

}
//
Caption .Visible = true;
for(int r=0;r{
for(int i=0;i{
worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
this.Caption.Text= " ["+ percent.ToString("0.00") +"%]...";
Application.DoEvents();
}
worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);

this.Caption.Visible= false;
this.Caption.Text= oldCaption;

range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);

range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;

if(ds1.Tables[0].Columns.Count>1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
}
workbook.Close(missing,missing,missing);
xlApp.Quit();
}



三、付注:
いずれもexeclのエクスポートを実現する機能であるがasp.Netとwinformのプログラムでは,実装されるコードがそれぞれ異なる.asp.Netでは、サーバ側でデータを読み出し、サーバ側でデータをms-execl形式でResponseでブラウザ(クライアント)に出力する.winformでは、クライアント(winform実行端がクライアントであるため)にデータを読み込み、クライアントがインストールしたofficeコンポーネントを呼び出し、読み込んだデータをexeclのワークブックに書きます.
 
  
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";// web.config downloadurl , +4
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine(" , , ");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// ,
Response.WriteFile(name); //
Response.End();