///
/// 使用NPOI產生EXCEL檔案 For C#
///
public void buildExcel()
{
SqlDataAdapter da;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
da = new SqlDataAdapter("SELECT * FROM EXP_TABLE", conn);
da.Fill(dt);
// 建立EXCEL物件
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet();
HSSFRow headerRow = sheet.CreateRow(0);
// 處理欄位標題.
foreach (DataColumn column in dt.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
// 處理欄位值.
int rowIndex = 1;
foreach (DataRow row in dt.Rows)
{
HSSFRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in dt.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
FileStream file = new FileStream(String.Format(@"C:\{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss")), FileMode.Create);
workbook.Write(file);
file.Close();
headerRow = null;
sheet = null;
workbook = null;
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dt.Dispose();
conn.Close();
conn.Dispose();
}
}
NPOI官方網站
http://npoi.codeplex.com/
NPOI 1.2教程
http://blog.csdn.net/tonyqus/archive/2009/11/29/4898453.aspx
Excel讀寫使用NPOI
http://www.dotblogs.com.tw/killysss/archive/2010/01/27/13344.aspx
張貼留言