C# 导出数据到EXCEL的方法

    方法一:
     /// <summary>
/// 把数据库的数据导出到Excel ,不会出现导出遇到格式的问题
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="strName">Sheet的名称</param>
/// <param name="strColumnName">要导出的列明</param>
/// 格式string[,] strColumnName = { { "companyNum", "公司货号" }, { "materialName", "材料名称" }, { "factory", "工厂" }}
/// <param name="strFileName">文件名(包括路径)</param>
/// <param name="strSum">是否是合计(可以为空)</param>
public void ExportToExcel(DataTable dt, string strName, string[,] strColumnName, string strFileName, string strSum)
{
//导出到execl
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Excel._Application excel = new Excel.Application();

try
{
if (strName.Length != 0)
{
try
{
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
}
catch
{
}
excel.Application.Workbooks.Add(true);

//excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
if (excel == null)
{
throw new Exception("EXCEL无法启动!");
}
Excel.Workbooks books = (Excel.Workbooks)excel.Workbooks;
Excel.Workbook book = (Excel.Workbook)(books.Add(miss));
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
sheet.Name = strName;
Excel.Range range;

//生成列名称
excel.Cells[1, 1] = "序号";
for (int i = 0; i < strColumnName.Length / strColumnName.Rank; i++)
{
excel.Cells[1, i + 2] = strColumnName[i, 1].ToString();
}

//填充数据
for (int i = 0; i < dt.Rows.Count; i++)
{
excel.Cells[i + 2, 1] = (i + 1).ToString();

for (int j = 0; j < strColumnName.Length / strColumnName.Rank; j++)
{
range = (Excel.Range)excel.Cells[i + 2, j + 2];
range.NumberFormatLocal = "@";
range.Value2 = dt.Rows[i][strColumnName[j, 0].ToString()].ToString();
}
}

if (strSum != null && strSum != "")
{
excel.Cells[dt.Rows.Count + 4, 1] = strSum;
}

book.SaveAs(strFileName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange
, miss, miss, miss, miss, miss);
books.Close();
excel.Workbooks.Open(strFileName, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
excel.Visible = true;
}
}

catch (Exception ex)
{
ExcelDispose(excel);
throw ex;
}
finally
{

GC.Collect();
}
} 方法二:
#region 导出Excel规则 会有格式错误,有些不是日期的格式,自动转为日期 。如 63-3 转为 Mar-63
/////////////////导出Excel处理//////////////////
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="thisDGV">传一个DataGridView</param>
public void ExportToExcel(DataTable dt)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel 工作表(*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出 Excel 文件到";

//saveFileDialog //保存对话框
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("GB2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i > 0)
{
str += "\t";
}
str += dt.Columns[i].ColumnName;
}

sw.WriteLine(str);

//写内容
for (int j = 0; j <dt.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k <dt.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dt.Rows[j][k].ToString();
}
sw.WriteLine(tempStr, Encoding.Default);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
}
#endregion

方法三:

#region -- 导出Excel不规则 按照模板导出 --

/// <summary>
/// 导出Excel
/// </summary>
/// <param name="strFilePath">模板文件路径</param>
/// <param name="strSaveFilePath">保存文件的路径</param>
/// <param name="dtMolds">模具列表</param>
/// <param name="strFileType">文件类型(xls,xlsx)</param>
public void OutExcel(string strFilePath, string strSaveFilePath, DataTable dtMolds, string strFileType)
{
DataTable dtMoDetail = dtMolds.DefaultView.ToTable(false, new string[] { "size", "shoeTree", "MD1", "MD2", "RB", "TPRcd", "guodong", "pvc" });
object objValue = System.Reflection.Missing.Value;

Excel._Application MyApp = new Excel.Application();
MyApp.Visible = true;
Excel.Range rng;
Excel.Range r1, r;
int columnCurrent = 1;
int rowNum = 0;
object Cell1, Cell2;
Excel.Range SourceRange;
try
{
Excel._Worksheet SourceSheet = (Excel._Worksheet)setExcelByVersion(strFilePath, ref MyApp).Sheets[1];

r1 = SourceSheet.get_Range("model", objValue); //型体
// rowCurrent1 = r1.Row; //当前位置
int startRow = r1.Row + 1; //开始填写行
rowNum = dtMolds.Rows.Count; //导出的个数

for (int i = 0; i < dtMolds.Rows.Count; i++)
{
#region -- 模具信息 --
DataRow dr = dtMolds.Rows[i];

#region 先填充明细
int detailCount = 0; //明细个数
for (int j = 0; j < dtMoDetail.Columns.Count; j++)
{
if (dtMoDetail.Rows[i][j].ToString() != "")
{
//明细
r = SourceSheet.get_Range("detail", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow + detailCount, columnCurrent];
rng.Value2 = dtMoDetail.Rows[i][j].ToString();
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中
detailCount++;
}
}
#endregion

#region 填充主信息
//
r = SourceSheet.get_Range("model", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["moldsId"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("BU", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["bussiness"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("moldTypes", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["moldType"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("origFactory", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["nowFactory"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);

////改后底厂
//r = SourceSheet.get_Range("nowFactory", objValue);
//columnCurrent = r.Column;
//rng = (Excel.Range)SourceSheet.Cells[rowCurrent1 + 1 + i, columnCurrent];
//rng.Value2 = dr["nowFactory"].ToString();

//
r = SourceSheet.get_Range("groupTpr", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["groupTpr"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("picture", objValue);
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
InsertPicture(SourceRange, SourceSheet, dr["picture"].ToString());

//
r = SourceSheet.get_Range("logo", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["logo"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("designerId", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["designerId"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("shoeTreeId", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["shoeTreeId"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);

//
r = SourceSheet.get_Range("shoeType", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["shoeType"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

//
r = SourceSheet.get_Range("remark", objValue);
columnCurrent = r.Column;
rng = (Excel.Range)SourceSheet.Cells[startRow, columnCurrent];
rng.Value2 = dr["remark"].ToString();
//合并单元格
Cell1 = SourceSheet.Cells[startRow, r.Column];
Cell2 = SourceSheet.Cells[startRow + detailCount - 1, r.Column];
SourceRange = SourceSheet.get_Range(Cell1, Cell2);
SourceRange.Merge(0);
rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
rng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中

startRow = startRow + detailCount; //设置下次开始的位置
#endregion

#endregion
}

string filename = "导出文件名自定义-" + "-" + DateTime.Now.ToString("yyyyMMdd");
string strDescFile = strSaveFilePath + filename + strFileType;
DeleteFile(strDescFile);
SourceSheet.SaveAs(strDescFile, objValue, objValue, objValue, objValue, objValue, objValue, objValue, objValue, objValue);
SourceSheet.Application.ActiveWorkbook.Close(false, objValue, objValue);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (MyApp.ActiveWorkbook != null)
{
MyApp.ActiveWorkbook.Close(false, objValue, objValue);
}
ExcelDispose(MyApp);
GC.Collect();
}
}
#endregion



posted @ 2012-01-13 10:36  戴眼镜的乌龟  阅读(611)  评论(0编辑  收藏  举报