asp.NetDataSetデータExcelに書き込みカスタム名をデフォルトフォルダに保存
using System;
using System.Web;
using Excel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
/// <summary>
/// DataSet Excel (C:\web\SaveFile)
/// </summary>
/// <param name="ds">System.Data.DataSet </param>
/// <param name="filename"> ( ) "Wenjian"</param>
public static void WriteExcel(System.Data.DataSet ds, string filename)
{
System.Data.DataTable dt = ds.Tables[0];
//dt.Columns[0]
//Excel.Application excel = new Excel.Application();// Excel
//excel.Application.Workbooks.Add(true );// Excel
//excel.Cells[ 1 , 1 ] = "First Row First Column";
//excel.Cells[ 1 , 2 ] = "First Row Second Column";
//excel.Cells[ 2 , 1 ] = "Second Row First Column";
//excel.Cells[2, 2] = "Second Row Second Column";
//excel.Visible = true; // Excel
// Application
Excel.Application xApp = new Excel.ApplicationClass();
xApp.Visible = false;
//// WorkBook , :
//Excel.Workbook xBook = xApp.Workbooks._Open(@"C:\web\SaveFile\az.xls",
//Missing.Value, Missing.Value, Missing.Value, Missing.Value
//, Missing.Value, Missing.Value, Missing.Value, Missing.Value
//, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Excel.Workbook xBook = xApp.Workbooks.Add(Missing.Value);//
// Sheet, :
Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1];
//Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet;
//// , Range
//Excel.Range rng1 = xSheet.get_Range("A1", Type.Missing);
//rng1.Value2 = "aaa";
//// , Range , Range
////Excel.Range rng2 = (Excel.Range)xSheet.Cells[1,2];
////rng2.Value2 = "bbb";
//((Excel.Range)xSheet.Cells[1, 2]).Value="ccc";
////
//Excel.Range rng3 = xSheet.get_Range("B2", Missing.Value);
//rng3.Value2 = "Hello";
//rng3.Interior.ColorIndex = 6; // Range
for (int i = 0; i < dt.Columns.Count; i++)
{
((Excel.Range)xSheet.Cells[1, i + 1]).Value = dt.Columns[i].ColumnName;
for (int j = 0; j < dt.Rows.Count; j++)
{
((Excel.Range)xSheet.Cells[j + 2, i + 1]).Value = dt.Rows[j][i];
}
}
string pFilePath = @"C:\web\SaveFile\" + filename ?? System.DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
//// : WorkBook
if (File.Exists(pFilePath))
{
File.Delete(pFilePath);
}
xBook.SaveAs(pFilePath,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
//// : WorkSheet
//xSheet.SaveAs(@"../SaveFile/CData2.xls",
//Missing.Value, Missing.Value, Missing.Value, Missing.Value,
//Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//
//xBook.Save();
xSheet = null;
xBook = null;
xApp.Quit(); // , Excel
xApp = null;
}
クラスライブラリExcelHelperにカプセル化
ダイレクトコール