Epplus (Excel元件)
3.
直接列出匯出成Excel的程式碼…
//若存在該檔案則先刪除
if
(File.Exists(sFilePath))
{
File.Delete(sFilePath);
}
//開檔
FileStream
fs = new FileStream(sFilePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
//載入Excel檔案
ExcelPackage
ep = new ExcelPackage(fs);
if
(ep.Workbook.Worksheets[sNewSheetName] == null)
//不存在該Sheet
{
//加入一個WorkSheet
var
ws = ep.Workbook.Worksheets.Add(sNewSheetName);
ws.View.ShowGridLines = true; //是否顯示格線
}
//取得WorkSheet
ExcelWorksheet
sheet = ep.Workbook.Worksheets[sNewSheetName ];
//設定起始列為3
int
startRowNumber = 3;
int
DataRowNumber = startRowNumber+1;
//寫入標題文字
for (int
i = 0; i < dataGridView.Columns.Count; i++)
{
//設值為欄位名稱
sheet.Cells[startRowNumber,
i + 1].Value = dataGridView.Columns[i].Name;
//設定樣式
sheet.Cells[startRowNumber, i +
1].AutoFitColumns(); //自動欄寬
//sheet.Column(i
+ 1).Width = 100;
sheet.Cells[startRowNumber,
i + 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
//欄位置中
sheet.Cells[startRowNumber,
i + 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
//儲存格框線
}
//寫入資料
int
ColCnt = dataGridView.Columns.Count; //欄位數
int RowCnt =
dataGridView.Rows.Count; //資料數
for
(int i = 0; i < RowCnt; i++)
{
for
(int j = 0; j < ColCnt; j++)
{
//讀值
string cellValue = "";
if (dataGridView.Rows[i].Cells[j].Value != null)
{
cellValue =
dataGridView.Rows[i].Cells[j].Value.ToString();
}
else
{
cellValue = "";
}
//寫值
sheet.Cells[DataRowNumber, j + 1].Value = cellValue;
//樣式設定
//sheet.Cells[DataRowNumber,
j + 1].AutoFitColumns(); //自動欄寬
sheet.Cells[DataRowNumber, j + 1].Style.HorizontalAlignment =
OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
//欄位置中
sheet.Cells[DataRowNumber,
j + 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
//儲存格框線
}
DataRowNumber++;
}
//存檔
ep.SaveAs(fs);
fs.Close();
//關閉資源
ep.Dispose();
ep = null;
MessageBox.Show("儲存成功! ");
今天發現要設定儲存格的顏色,一定要先指定PatternType!!
回覆刪除var _cell = sheet.Cells[10,9];
//設定樣式
_cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
_cell.Style.Fill.BackgroundColor.SetColor(Color.Yellow); //必須先設定PatternType 才能指定Fill顏色 !!
如果要合併儲存格...
回覆刪除sheet.Cells["A1:I1"].Merge = true; //合併A1-I1儲存格
sheet.Cells["A1:I1"].Value = "XXXX查詢報表";
sheet.Cells["A1:I1"].Style.Font.Size = 20;
sheet.Cells["A1:I1"].Style.Font.Bold = true;
sheet.Cells["A1:I1"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
如果是寫WEB,要匯出Excel則如下寫法 :
回覆刪除//載入Excel檔案
ExcelPackage ep = new ExcelPackage();
//寫檔...
//開始匯出Excel
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(ep.GetAsByteArray());
//Response.End();
另外如果是從GridView匯出資料,如果是空值的欄位,匯出時會帶出 "& nbsp;"
回覆刪除所以我們在寫檔時,就要手動把它修正,請參考下面寫法(用Replace)
cellValue = GridView.Rows[i].Cells[j].Text.ToString().Replace("& nbsp;", ""); ;