http://blog.csdn.net/coderk2014/article/details/50185163
一、下载引用
下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2007版需要此dll)。
二、excel转datatable类
三、结果

四、写入excel类
-
public static bool DataTableToExcel(DataTable dt)
-
{
-
bool result = false;
-
IWorkbook workbook = null;
-
FileStream fs = null;
-
IRow row = null;
-
ISheet sheet = null;
-
ICell cell = null;
-
try
-
{
-
if (dt != null && dt.Rows.Count > 0)
-
{
-
workbook = new HSSFWorkbook();
-
sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
-
int rowCount = dt.Rows.Count;//行数
-
int columnCount = dt.Columns.Count;//列数
-
-
//设置列头
-
row = sheet.CreateRow(0);//excel第一行设为列头
-
for (int c = 0; c < columnCount; c++)
-
{
-
cell = row.CreateCell(c);
-
cell.SetCellValue(dt.Columns[c].ColumnName);
-
}
-
-
//设置每行每列的单元格,
-
for (int i = 0; i <rowCount; i++)
-
{
-
row = sheet.CreateRow(i+1);
-
for (int j = 0; j < columnCount; j++)
-
{
-
cell = row.CreateCell(j);//excel第二行开始写入数据
-
cell.SetCellValue(dt.Rows[i][j].ToString());
-
}
-
}
-
using (fs = File.OpenWrite(@"D:/myxls.xls"))
-
{
-
workbook.Write(fs);//向打开的这个xls文件中写入数据
-
result = true;
-
}
-
}
-
return result;
-
}
-
catch (Exception ex)
-
{
-
if (fs != null)
-
{
-
fs.Close();
-
}
-
return false;
-
}
-
}
结果如下:

源码地址:http://download.csdn.net/detail/coderk2014/9328779
|