SHOWcode
2018年4月11日 星期三
C#.NET NPIO GridView 匯出
//using NPOI;
//using NPOI.HSSF.UserModel;
//using NPOI.XSSF.UserModel;
//using NPOI.SS.UserModel;
//using System.IO;
#region NPIO GridView 匯出
public void GridToExcel(string fileName, DataGridView dgv)
{
if (dgv.Rows.Count == 0)
{
return;
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel 2003格式|*.xls";
sfd.FileName = fileName + DateTime.Now.ToString("yyyyMMdd_ss");
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)wb.CreateSheet(fileName);
HSSFRow headRow = (HSSFRow)sheet.CreateRow(0);
for (int i = 0; i < dgv.Columns.Count; i++)
{
HSSFCell headCell = (HSSFCell)headRow.CreateCell(i, CellType.String);
headCell.SetCellValue(dgv.Columns[i].HeaderText);
}
for (int i = 0; i < dgv.Rows.Count; i++)
{
HSSFRow row = (HSSFRow)sheet.CreateRow(i + 1);
for (int j = 0; j < dgv.Columns.Count; j++)
{
HSSFCell cell = (HSSFCell)row.CreateCell(j);
if (dgv.Rows[i].Cells[j].Value == null)
{
cell.SetCellType(CellType.Blank);
}
else
{
if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Int32"))
{
cell.SetCellValue(Convert.ToInt32(dgv.Rows[i].Cells[j].Value));
}
else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.String"))
{
cell.SetCellValue(dgv.Rows[i].Cells[j].Value.ToString());
}
else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Single"))
{
cell.SetCellValue(Convert.ToSingle(dgv.Rows[i].Cells[j].Value));
}
else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Double"))
{
cell.SetCellValue(Convert.ToDouble(dgv.Rows[i].Cells[j].Value));
}
else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Decimal"))
{
cell.SetCellValue(Convert.ToDouble(dgv.Rows[i].Cells[j].Value));
}
else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.DateTime"))
{
cell.SetCellValue(Convert.ToDateTime(dgv.Rows[i].Cells[j].Value).ToString("yyyy-MM-dd"));
}
}
}
}
for (int i = 0; i < dgv.Columns.Count; i++)
{
sheet.AutoSizeColumn(i);
}
using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
{
wb.Write(fs);
}
MessageBox.Show("匯出成功!", "匯出出提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
訂閱:
張貼留言 (Atom)
Jenkins-mail
參考:http://www.linuxea.com/1767.html 前置作業略過~有空再補 Mailer Plugin post { success { emailext ( subject: &...
-
ASP.NET刷新頁面的六種方法 第一: private void Button1_Click( object sender, System.EventArgs e ) { Response.Redirect( Request.Url.ToSt...
-
foreach (string fname in System.IO.Directory.GetFileSystemEntries(@"C:\Users\joshs")) { //if (fn...
沒有留言:
張貼留言