|
■No13829 (春紫苑 さん) に返信
> Windows Vista, Visual Studio 2005, C# です。
セットするExcelのシートにフォーマットがある場合にうまく動くかどうかわかりませんが、
Range.Value2に配列を設定するのでは、目的に合わないのかな?
#これだとDbNullのままでも平気みたいな・・・。
試したのはこんなコードです。
DataSet1 ds = new DataSet1();
DataSet1TableAdapters.EmployeesTableAdapter adapter = new ExcelConsole.DataSet1TableAdapters.EmployeesTableAdapter();
adapter.Fill(ds.Employees);
Object[,] excelArray = new Object[ds.Employees.Rows.Count, ds.Employees.Columns.Count];
Int32 rowNumber = 0;
Int32 colNumber = 0;
foreach (DataSet1.EmployeesRow row in ds.Employees.Rows)
{
foreach (DataColumn column in ds.Employees.Columns)
{
if (row[column] == DBNull.Value)
{
Console.WriteLine("{0}:{1}", column.ColumnName, "DbNull");
}
//excelArray[rowNumber, colNumber] = (row[column] == DBNull.Value) ? null : row[column];
excelArray[rowNumber, colNumber] = row[column];
colNumber++;
}
rowNumber++;
colNumber = 0;
}
Application xlApp = new Application();
xlApp.Visible = true;
Workbooks xlbooks = xlApp.Workbooks;
Workbook xlbook = xlbooks.Add("");
Sheets xlsheets = xlbook.Worksheets;
Worksheet xlsheet = xlsheets[1] as Worksheet;
Range xlrange = xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[ds.Employees.Rows.Count, ds.Employees.Columns.Count]);
xlrange.Value2 = excelArray;
Marshal.ReleaseComObject(xlrange);
Marshal.ReleaseComObject(xlsheet);
Marshal.ReleaseComObject(xlsheets);
xlbook.Saved = true;
Marshal.ReleaseComObject(xlbook);
Marshal.ReleaseComObject(xlbooks);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
Rangeの大きさとか、ReleaseComObjectとかは割と適当に書いていますので、適宜確認して下さい。
|