public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle) //實現導出 EXcel 和 滾動條功能
{
if (dgv.Rows.Count == 0)
return false;
//建立Excel對象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
progressBar.Maximum = dgv.RowCount;
progressBar.Step = dgv.RowCount /40;
progressBar.Value = 0;
//labelvalue.Visible = true; //先顯示Label標簽才能置於 進度條之上
//labelvalue.Parent = progressBar;
//labelvalue.Location = new Point(progressBar.Width/2-labelvalue.Width/2,progressBar.Height/2-labelvalue.Height/2); //計算在父容器 的 居中位置
var point = new Point(progressBar.Width / 2 - labelvalue.Width / 2, progressBar.Height / 2 - labelvalue.Height / 2);
progressBar.Visible = true;
Graphics g = progressBar.CreateGraphics(); //在滾動條上 創建 GDI+繪圖對象
//生成字段名稱
for (int i = 0; i < dgv.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
}
//填充數據
for (int i = 0; i < dgv.RowCount - 1; i++)
{
for (int j = 0; j < dgv.ColumnCount; j++)
{
//if (dgv[j, i].ValueType == typeof(DateTime))
//{
// excel.Cells[i + 2, j + 1].NumberFormatLocal = "yyyy-MM-dd HH:mm:ss";
//}
if (dgv[j, i].ValueType == typeof(DateTime))
{
excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString(); //EXcel 文本方式顯示
}
else
{
excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();
}
}
if((i+1)% progressBar.Step == 0) //判斷遞增進度
{
progressBar.PerformStep();
labelvalue.Text = String.Format("加載中:{0:0%}", (float)progressBar.Value/ dgv.RowCount); //先轉換浮點數運算,再把浮點數轉百分比
if (progressBar.Maximum / progressBar.Value < 2)
{
g.DrawString(labelvalue.Text, new Font("Arial", 10), Brushes.Yellow, point); //在居中位置繪制 進度數值
}
else
{
g.DrawString(labelvalue.Text, new Font("Arial", 10), Brushes.Blue, point); //在居中位置繪制 進度數值 變色適應背景
}
}
}
labelvalue.Visible = false;
progressBar.Visible = false;
excel.Visible = true; //導出完成彈出表格 以防出錯
return true;
}
