C# 把DataTable数据写入Excel文件的方法

使用C#把DataTable内数据写入Excel的方法收集。

一、使用OpenXml方式

 

//以下是由OpenXml方式把DataTable生成Excel的例子:
public void ExportDataTable(
DataTable table,
string exportFile)
{
//create the empty spreadsheet template and save the file
//using the class generated by the Productivity tool
ExcelDocument excelDocument = new ExcelDocument();
excelDocument.CreatePackage(exportFile);

//populate the data into the spreadsheet
using (SpreadsheetDocument spreadsheet =
SpreadsheetDocument.Open(exportFile, true))
{
WorkbookPart workbook = spreadsheet.WorkbookPart;
//create a reference to Sheet1
WorksheetPart worksheet = workbook.WorksheetParts.Last();
SheetData data = worksheet.Worksheet.GetFirstChild();

//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)1;

foreach (DataColumn column in table.Columns)
{
Cell headerCell = createTextCell(
table.Columns.IndexOf(column) + 1,
1,
column.ColumnName);

header.AppendChild(headerCell);
}
data.AppendChild(header);

//loop through each data row
DataRow contentRow;
for (int i = 0;i < table.Rows.Count; i++)
{
contentRow = table.Rows[i];
data.AppendChild(createContentRow(contentRow, i + 2));
}
}
}

private Cell createTextCell(
int columnIndex,
int rowIndex,
object cellValue)
{
Cell cell = new Cell();

cell.DataType = CellValues.InlineString;
cell.CellReference = getColumnName(columnIndex) + rowIndex;

InlineString inlineString = new InlineString();
Text t = new Text();

t.Text = cellValue.ToString();
inlineString.AppendChild(t);
cell.AppendChild(inlineString);

return cell;
}

private Row createContentRow(
DataRow dataRow,
int rowIndex)
{
Row row = new Row

{
RowIndex = (UInt32)rowIndex
}; 

for (int i = 0; i < dataRow.Table.Columns.Count; i++)
{
Cell dataCell = createTextCell(i + 1, rowIndex, dataRow[i]);
row.AppendChild(dataCell);
}
return row;
}

private string getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier;

while (dividend > 0)
{
modifier = (dividend – 1) % 26;
columnName =
Convert.ToChar(65 + modifier).ToString() + columnName;
dividend = (int)((dividend – modifier) / 26);
}

return columnName;
}

注意:该方法需要微软的OpenXML SDK 2.0支持。

 

二、OleDB方式

public string ExportTable2ExcelFile(DataTable dt, string strWorkSheetName)//, string ModelFile)
        {
            if (File.Exists(this.FileName) == false)
            {
                return "指定文件不存在!";
            }

            if (dt == null)
            {
                return "数据不能为空!";
            }

            if (strWorkSheetName.ToString() == "")
            {
                return "数据表名不可以为空!";
            }
            dt.TableName = strWorkSheetName;

            int iRows = dt.Rows.Count;
            int iCols = dt.Columns.Count;

            StringBuilder stringBuilder;

            if (iRows == 0)
            {
                return "没有可导入数据!";
            }

            stringBuilder = new StringBuilder();

            //先查看此Excel中是否有相关Table,如果有的话就删除,然后导入新的。
            //生成创建表的脚本
            stringBuilder.Append("CREATE TABLE ");
            stringBuilder.Append(dt.TableName + " ( ");
            for (int i = 0; i < iCols; i++)
            {
                //此处是本版本改进中最实用的地方
                string strType = GetOleDataType(dt.Columns[i]);
                if (i < iCols - 1)
                    stringBuilder.Append(string.Format("{0} {1},", dt.Columns[i].ColumnName, strType));
                else
                    stringBuilder.Append(string.Format("{0} {1})", dt.Columns[i].ColumnName, strType));
            }
            using (this.Connection)
            {
                //控制进度条
                int iCount = 1, iTotal = dt.Rows.Count + 4;
                OleDbCommand objCmd = new OleDbCommand();
                objCmd.Connection = this.Connection;

                //插入新表
                objCmd.CommandText = stringBuilder.ToString();

                try
                {
                    this.Connection.Open();
                    //插入新表
                    objCmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    return "在Excel中创建表失败!错误信息:" + e.Message;
                }

                stringBuilder.Remove(0, stringBuilder.Length);

                stringBuilder.Append("INSERT INTO ");
                stringBuilder.Append(dt.TableName + " ( ");

                //先插入标头
                for (int i = 0; i < iCols; i++)
                {
                    if (i < iCols - 1)
                        stringBuilder.Append(dt.Columns[i].ColumnName + ",");
                    else
                        stringBuilder.Append(dt.Columns[i].ColumnName + ") values (");
                }

                for (int i = 0; i < iCols; i++)
                {
                    if (i < iCols - 1)
                        stringBuilder.Append("@" + dt.Columns[i].ColumnName + ",");
                    else
                        stringBuilder.Append("@" + dt.Columns[i].ColumnName + ")");
                }
                //建立插入动作的Command
                objCmd.CommandText = stringBuilder.ToString();
                OleDbParameterCollection oleParam = objCmd.Parameters;

                oleParam.Clear();
                for (int i = 0; i < iCols; i++)
                {
                    OleDbType oleDbType = GetRefOleDataType(dt.Columns[i]);

                    //此处是本版本改进中最实用的地方
                    oleParam.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, oleDbType));
                }
                //遍历DataTable将数据插入新建的Excel文件中
                foreach (DataRow row in dt.Rows)
                {
                    for (int i = 0; i < oleParam.Count; i++)
                    {
                        oleParam[i].Value = row[i];
                    }

                    objCmd.ExecuteNonQuery();
                }
                if (this.Connection.State == ConnectionState.Open)
                {
                    this.Connection.Close();
                }
                return "数据已成功导入Excel!";
            }
        }

该方法中的OleDB连接Connection的具体实现和 Excel文件名我就没有贴出来了,朋友们可以自己去实现。

注意:该方法不能自动创建Excel文件,所以使用该方法需要先创建好Excel文件才能使用。

 

三、使用Com组件实现Excel数据写入

该方法在网上列子较多,由于时间关系,这里我就不代码列举了(以后有时间再来补上)。

注意:该方法需要引用Com组件(Microsoft Office 12.0 Object Library :Office 2007;Microsoft Office 14.0 Object Library :Office 2010;

Microsoft Office 8.0 Object Library:Office2003)。

 

引用一下链接:http://blog.csdn.net/tider_ys/article/details/6590060  (.net 3种自动导出带图片的excel方法)可以借鉴学习。


 

你可能感兴趣的:(Excel,数据库,c#,导入)