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");//創(chuàng)建一個名稱為Sheet0的表
-
int rowCount = dt.Rows.Count;//行數(shù)
-
int columnCount = dt.Columns.Count;//列數(shù)
-
-
//設置列頭
-
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第二行開始寫入數(shù)據(jù)
-
cell.SetCellValue(dt.Rows[i][j].ToString());
-
}
-
}
-
using (fs = File.OpenWrite(@"D:/myxls.xls"))
-
{
-
workbook.Write(fs);//向打開的這個xls文件中寫入數(shù)據(jù)
-
result = true;
-
}
-
}
-
return result;
-
}
-
catch (Exception ex)
-
{
-
if (fs != null)
-
{
-
fs.Close();
-
}
-
return false;
-
}
-
}
結果如下:

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