<span style="font-family:SimHei;font-size:12px;">public DataSet execl(DataSet ds, string filename)//ds中包含几个table就会有几个sheet生成
{
string absFileName;
int tablecount = ds.Tables.Count;
if (tablecount <= 0)
return ds;
int index = 0;
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbook xlBook = null;
Microsoft.Office.Interop.Excel.Worksheet xlSheet = null;
int rowIndex = 1;
int colIndex = 0;
object missing = Missing.Value;
List<System.Data.DataTable> listTable = new List<System.Data.DataTable>();
try
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlBook = xlApp.Workbooks.Add(true);
foreach (System.Data.DataTable dt in ds.Tables)
{
index++;
rowIndex = 1;
colIndex = 0;
xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.Worksheets[1];
xlSheet.Name = dt.TableName;
//格式设置
for (int i = 1; i <= ds.Tables[0].Columns.Count; i++)
{
Range allDataWithTitleRange = xlSheet.get_Range(xlApp.Cells[1, i], xlApp.Cells[1, i]);
allDataWithTitleRange.Select();
allDataWithTitleRange.ColumnWidth = 20;//列宽为20
allDataWithTitleRange.Font.Size = 13;//设置字体大小
allDataWithTitleRange.Font.Underline = false;//设置字体是否有下划线
allDataWithTitleRange.Font.Name = "新体"; //设置字体的种类
allDataWithTitleRange.HorizontalAlignment = XlHAlign.xlHAlignCenter; //设置字体在单元格内的对其方式
}
foreach (DataColumn Col in dt.Columns)
{
colIndex = colIndex + 1;
xlApp.Cells[1, colIndex] = " " + Col.ColumnName;
}
int rowNum = dt.Rows.Count;
int colNum = dt.Columns.Count;
string[,] finalData = new string[rowNum, colNum];
for (int i = 0; i < rowNum; i++)
{
for (int j = 0; j < colNum; j++)
{
finalData[i, j] = dt.Rows[i][j].ToString();
}
}
xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[1, colIndex]).Font.Bold = true;
xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[rowIndex, colIndex]).Borders.LineStyle = 1;
xlSheet.get_Range(xlSheet.Cells[2, 1], xlSheet.Cells[rowNum + 1, colNum]).Value2 = finalData;
xlSheet.get_Range(xlSheet.Cells[2, 1], xlSheet.Cells[rowNum + 1, colNum]).NumberFormatLocal = "@"; //设置单元格格式为文本
if (index < tablecount)
xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.Worksheets.Add(missing, missing, missing, missing);
}
}
finally
{
string exportDir = "~/ExcelData/";//该文件夹事先在服务器上建好
//设置文件在服务器上的路径
absFileName = HttpContext.Current.Server.MapPath(System.IO.Path.Combine(exportDir, filename));
xlBook.SaveCopyAs(absFileName);
xlBook.Close(false, null, null);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
xlBook = null;
xlApp = null;
xlSheet = null;
GC.Collect();
}
return ds;
}
}</span>
C#导出execl文件
最新推荐文章于 2022-08-06 12:08:47 发布