public static System.Data.DataSet ReadExcel(string filename,bool firstRowIsColumnsName,ref bool readFlag,ref string reMsg)
{
System.Data.DataSet ds=new System.Data.DataSet();
Workbook workbook=new Workbook();
try{
workbook.Open(filename);
for(int n=0;n<workbook.Worksheets.Count;n++)
{
Cells cells=workbook.Worksheets[n].Cells;
System.Data.DataTable dt=new System.Data.DataTable();
dt.TableName=workbook.Worksheet[n].Name;
bool flag=firstRowIsColumnsName&cells.MaxDataRow>0;
for(int i=0;i<cells.MaxColumn+1;i++)
{
dt.Columns.Add(flag?cells[0,i].StringValue.Trim():"col"+i+ToString());
}
for(int i=(firstRowIsColumsName?1:0);i<cells.MaxDataRow+1;i++)
{
System.Data.DataRow dr=dt.NewRow();
for(int j=0;j<cells.MaxDataColumns+1;j++)
{
dr[j]=cells[i,j].StringValue.Trim();
}
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
}
readFlag=true;
}
catch(Exception es)
{
readFlag=false;
reMsg=es.ToString;
}
return ds;
}
//=---------------将dataSet导出到Excel
public static void OutPutExcelForDataSet(System.Data.DataSet dsExport,string filename)
{
Aspose.Cells.Licens lic=new Asponse.Cells.License();
lic.SetLicense("Aspose.Cells.lic");
Workbook xlsBK=new Asponse.Cells.Workbook();
Worksheet xlsST=null;
for(int n=0;n<dsExport.Tables.Count;n++)
{
xlsST = xlsBK.Worksheets[n];
for (int j = 0; j < dsExport.Tables[n].Columns.Count; j++)
{
xlsST.Cells[0, j].PutValue(dsExport.Tables[n].Columns[j].ColumnName);
}
for (int i = 0; i < dsExport.Tables[n].Rows.Count; i++)
{
for (int j = 0; j < dsExport.Tables[n].Columns.Count; j++)
{
xlsST.Cells[i + 1, j].PutValue(dsExport.Tables[n].Rows[i][j]);
}
}
}
System.IO.MemoryStream ms = xlsBK.SaveToStream();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/x-msexcel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + filename + ".xls");
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
ms.Close();
}
=================将dataTable读取到Excel中。
/// <param name="filename">输出文件名</param>
public static void OutPutExcelWinForm(System.Data.DataTable dtExport, string filename)
{
Aspose.Cells.License lic = new Aspose.Cells.License();
lic.SetLicense("Aspose.Cells.lic");
Workbook xlsBK = new Aspose.Cells.Workbook();
Worksheet xlsST = null;
xlsST = xlsBK.Worksheets[0];
for (int j = 0; j < dtExport.Columns.Count; j++)
{
xlsST.Cells[0, j].PutValue(dtExport.Columns[j].ColumnName);
}
for (int i = 0; i < dtExport.Rows.Count; i++)
{
for (int j = 0; j < dtExport.Columns.Count; j++)
{
xlsST.Cells[i + 1, j].PutValue(dtExport.Rows[i][j]);
}
}
xlsBK.Save(filename);
}