using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace zzz.BusinessSystem
{
public static class ExcelHelp
{
/// <summary>
/// DataTable导出到Excel,效率比较慢,是正常格式的Excel
/// </summary>
/// <param name="dt"> DataTable对象</param>
/// <param name="FileName">文件路径+文件名 (例如:"E:\\aa.xlsx")</param>
public static void DataTable_Excel(System.Data.DataTable dt, string FileName)
{
if (dt == null)
return;
int rowNumber = dt.Rows.Count;
int columnNumber = dt.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
//System.Windows.Forms.Application xlapp = new System.Windows.Forms.Application();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列明导入Excel的第一行
foreach (DataColumn dc in dt.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//
for (int i = 0; i < rowNumber; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNumber; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dt.Rows[i][j].ToString();
}
}
//xlSheet.SaveAs(Page.Server.MapPath(".") & "\ExcelFolder\download.xls")
xlBook.SaveAs(FileName);
}
#region winform 导出
public static void win_DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
if (tmpDataTable == null)
return;
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列名导入Excel表第一行
foreach (DataColumn dc in tmpDataTable.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
}
}
//xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
xlBook.SaveCopyAs(strFileName);
}
public static void Win_DataTableToExcel(System.Data.DataTable dt, string saveFileName)
{
if (dt == null) return;
//-***************获取excel对象***************
// string saveFileName = "";
TimeSpan dateBegin = new TimeSpan(DateTime.Now.Ticks);
bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = "导入记录查询结果 " + DateTime.Today.ToString("yyyy-MM-dd");
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法启动Excel,可能您未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbook workbook = xlApp.Workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range;
// 列索引,行索引,总列数,总行数
int colIndex = 0;
int RowIndex = 0;
int colCount = dt.Columns.Count;
int RowCount = dt.Rows.Count;
// *****************获取数据*********************
//dataGrid1.CaptionVisible = true;
//dataGrid1.CaptionText = "正在导出数据";
// 创建缓存数据
object[,] objData = new object[RowCount + 1, colCount];
// 获取列标题
for (int i = 0; i < dt.Columns.Count; i++)
{
objData[RowIndex, colIndex++] = dt.Columns[i].Caption; // dgv.Columns[i].HeaderText;
}
// 获取具体数据
for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
{
for (colIndex = 0; colIndex < colCount; colIndex++)
{
objData[RowIndex, colIndex] = dt.Rows[RowIndex - 1][colIndex];
}
}
//********************* 写入Excel*******************
//range = worksheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, colCount]);
//range.Value2 = objData;
range = worksheet.Range[xlApp.Cells[2, 1], xlApp.Cells[RowCount + 1, colCount]];
range.Value = objData;
System.Windows.Forms.Application.DoEvents();
//*******************设置输出格式******************************
//设置顶部説明 合并的单元格
range = worksheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, colCount]);
range.MergeCells = true;
range.RowHeight = 38;
range.Font.Bold = true;
range.Font.Size = 14;
range.Font.ColorIndex = 10;//字体颜色
xlApp.ActiveCell.FormulaR1C1 = "导入记录查询结果";
//特殊数字格式
range = worksheet.get_Range(xlApp.Cells[2, colCount], xlApp.Cells[RowCount, colCount]);
// range.NumberFormat = "yyyy-MM-dd hh:mm:ss";
xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
range = worksheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colCount]);
// range.Interior.ColorIndex = 10;//背景色
range.Font.Bold = true;
range.RowHeight = 20;
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();//强行销毁
TimeSpan dateEnd = new TimeSpan(DateTime.Now.Ticks);
TimeSpan tspan = dateBegin.Subtract(dateEnd).Duration();
MessageBox.Show("导出成功,用时" + tspan.ToString() + "秒");
if (fileSaved && System.IO.File.Exists(saveFileName))
System.Diagnostics.Process.Start(saveFileName); //保存成功后打开此文件
}
public static void Win_ExportExcel(System.Data.DataTable dt, string fileName)
{
if (dt == null) return;
string saveFileName = "";
bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName + DateTime.Now.ToString("yyyyMMddhhmmss");
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Workbooks workbooks = xlApp.Workbooks;
Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
Range range;
string oldCaption = DateTime.Now.ToString("yyyy-MM-dd");
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
worksheet.Cells[1, 1] = DateTime.Now.ToString("yyyy-MM-dd");
//写入字段
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
range = (Range)worksheet.Cells[2, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//写入数值
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Rows[r][i].GetType().FullName == "System.DateTime")
{
worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i].ToString();
}
else
{
worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
}
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
//this.lbl_process.Text = "正在导出数据[" + percent.ToString("0.00") + "%]..."; //这里可以自己做一个label用来显示进度.
System.Windows.Forms.Application.DoEvents();
}
//this.lbl_process.Visible = false;
range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]];
range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);
range.Borders[XlBordersIndex.xlInsideHorizontal].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
range.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
if (dt.Columns.Count > 1)
{
range.Borders[XlBordersIndex.xlInsideVertical].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
range.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;
range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
}
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();//强行销毁
if (fileSaved && File.Exists(saveFileName))
{
//System.Diagnostics.Process.Start(saveFileName);
MessageBox.Show("数据导出成功!", "美承零售系统");
}
}
public static void Win_DataGridViewToExcel(DataGridView dgv)
{
SaveFileDialog dlg = new SaveFileDialog();
string saveFileName = "";
bool fileSaved = false;
dlg.Filter = "Execl files (*.xls)|*.xls";
dlg.FilterIndex = 0;
dlg.RestoreDirectory = true;
dlg.CreatePrompt = true;
dlg.Title = "保存为Excel文件";
dlg.FileName = "导出数据" + DateTime.Now.ToString("yyyyMMddhhmmss");
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
if (dgv.Rows.Count == 0)
return;
if (dlg.ShowDialog() == DialogResult.OK)
{
saveFileName = dlg.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Stream myStream;
myStream = dlg.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Columns[i].Visible == true)
{
if (i > 0)
{
columnTitle += "\t";
}
columnTitle += dgv.Columns[i].HeaderText;
}
}
sw.WriteLine(columnTitle);
//写入列内容
for (int j = 0; j < dgv.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dgv.Columns.Count; k++)
{
if (dgv.Columns[k].Visible == true)
{
if (k > 0)
{
columnValue += "\t";
}
if (dgv.Rows[j].Cells[k].Value == null)
columnValue += "";
else
columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
}
}
sw.WriteLine(columnValue);
}
fileSaved = true;
}
catch (Exception e)
{
fileSaved = false;
MessageBox.Show(e.ToString(), "美承零售系统", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
finally
{
sw.Close();
myStream.Close();
}
if (fileSaved && File.Exists(saveFileName))
{
MessageBox.Show("数据导出成功!", "美承零售系统", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
/// <summary>
/// 到处数据 lihui
/// </summary>
/// <param name="dt"></param>
/// <param name="strFileName"></param>
public static void Win_DataTabletoExcel1(System.Data.DataTable dt, string strFileName)
{
if (dt == null) return;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = strFileName + DateTime.Now.ToString("yyyyMMddhhmmss");
if (saveDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
string saveFileName = "";
bool fileSaved = false;
Microsoft.Office.Interop.Excel.Application xlApp;
Workbooks workbooks;
Workbook workbook;
Worksheet worksheet;
Range range;
saveFileName = saveDialog.FileName;
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
return;
}
workbooks = xlApp.Workbooks;
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
// string oldCaption = DateTime.Now.ToString("yyyy-MM-dd");
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
worksheet.Cells[1, 1] = string.Format("日期:{0}",DateTime.Now.ToString("yyyy-MM-dd"));
//写入字段
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
range = (Range)worksheet.Cells[2, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//写入数值
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Rows[r][i].GetType().FullName == "System.DateTime")
{
worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i].ToString();
}
else
{
range = (Range)worksheet.Cells[r + 3, i + 1];
range.NumberFormat = "@";
worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
}
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
}
range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]];
range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);
range.Borders[XlBordersIndex.xlInsideHorizontal].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
range.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
if (dt.Columns.Count > 1)
{
range.Borders[XlBordersIndex.xlInsideVertical].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
range.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;
range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
}
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();//强行销毁
if (fileSaved && File.Exists(saveFileName))
{
MessageBox.Show("数据导出成功!", "美承零售系统");
}
}
/// <summary>
/// 导出无标题数据 周吉敏---销售发票列表中导出出库明细
/// </summary>
/// <param name="dt"></param>
/// <param name="strFileName"></param>
public static void Win_StocktoExcel(System.Data.DataTable dt, string strFileName)
{
if (dt == null) return;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = strFileName;
if (saveDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
string saveFileName = "";
bool fileSaved = false;
Microsoft.Office.Interop.Excel.Application xlApp;
Workbooks workbooks;
Workbook workbook;
Worksheet worksheet;
Range range;
saveFileName = saveDialog.FileName;
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
return;
}
workbooks = xlApp.Workbooks;
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
// string oldCaption = DateTime.Now.ToString("yyyy-MM-dd");
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
// worksheet.Cells[1, 1] = string.Format("日期:{0}", DateTime.Now.ToString("yyyy-MM-dd"));
//写入字段
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//写入数值
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Rows[r][i].GetType().FullName == "System.DateTime")
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
else
{
range = (Range)worksheet.Cells[r + 2, i + 1];
range.NumberFormat = "@";
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
}
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
}
range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 1, dt.Columns.Count]];
range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);
range.Borders[XlBordersIndex.xlInsideHorizontal].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
range.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
if (dt.Columns.Count > 1)
{
range.Borders[XlBordersIndex.xlInsideVertical].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
range.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;
range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
}
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();//强行销毁
if (fileSaved && File.Exists(saveFileName))
{
MessageBox.Show("数据导出成功!", "美承进销存系统");
}
}
#endregion
}
}