通过微软的组件 操作 Excel2007

xls 文件有一个问题就是单独的表记录不能超过65535。这一点有时是不能被接受的。为了将大数据保存成excel,我找了很多的插件。可是不幸的是我都失败了。可以用的支持xlsx格式的插件我是一个也没看找到。有哪位大哥知道可以简单操作xlsx格式文件的方法的,给小弟留个言。这里我附上使用微软组件的方式操作xlsx格式文件的方法。效率不是很高,应该说是完全没有。

首先要应用微软的组件。2007是一个什么什么12.0的版本。改天附图。

protected override void Save(IReportData data,
YJC.Toolkit.Data.IColumnMappingCollection mappings,
string path)
{
_Application xlApp
= null;
_Workbook xlWorkbook
= null;
_Worksheet xlWorksheet
= null;
System.Reflection.Missing oMissing
= System.Reflection.Missing.Value;
try
{
xlApp
= new ApplicationClass();
xlApp.Visible
= false;
xlWorkbook
= xlApp.Workbooks.Add(oMissing);
xlWorksheet
= xlWorkbook.Worksheets.Add(oMissing, oMissing, 1, oMissing)
as _Worksheet;
xlWorksheet.Name
= "sheel1";
int head = 1;
foreach (var col in mappings.ColumnMappings)
{
Range r
= (Range)(xlWorksheet.Cells[1, head]);
r.NumberFormatLocal
= "";
xlWorksheet.Cells[
1, head] = col.DisplayName;
head
++;
}
int rowNUM = 2;
foreach (var row in data.Rows)
{
int colNUM =1;
foreach (var col in mappings.ColumnMappings)
{
if (col.DataType == XmlDataType.DateTime || col.DataType == XmlDataType.Date)
{
DateTime dateTime;
if (DateTime.TryParse(row[ReportUtil.GetDisplayFieldName(col)].ToString(), out dateTime))
{
xlWorksheet.Cells[rowNUM, colNUM]
= dateTime.ToShortDateString();
}
else
xlWorksheet.Cells[rowNUM, colNUM]
= "";
}
else
{
xlWorksheet.Cells[rowNUM, colNUM]
=
row[ReportUtil.GetDisplayFieldName(col)];
}
colNUM
++;
}
rowNUM
++;
}
xlWorkbook.SaveAs(path, oMissing, oMissing, oMissing, oMissing, oMissing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, oMissing,
oMissing, oMissing, oMissing, oMissing);
xlApp.Quit();
}
catch (Exception ex)
{
//todo
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp
= null;
//GC.Collect();可有可无
}
}

需要注意的一点是这里的计数是从1开始的。还有就是这里可以通过NumberFormit属性设置单元格的样式。改天附上带具体样式的代码。

回家

posted @ 2011-09-19 22:05  水逍遥  阅读(209)  评论(0)    收藏  举报