如何更快的将数据导入Excel
代码:/Files/zhuqil/ExportDataInExcel.rar
这篇文章将介绍3种方式将数据导入Excel:
1、基本方法:一格一格地拷贝
2、使用文件流StreamWriter对象:将流写入文件
3、拷贝对象的方法:将数据复制到数组,然后直接粘贴到Excel的workbook。
基本方法
使用基本的拷贝方法将会花费大量的时间。使用文件文件流或者拷贝对象的方法将比基本方法快很多。
你必须添加一个Excel COM Object 的引用到你的应用程序之中。我将要声明两个对象,Ex为Excel.Application类型。Ws为Excel.Worksheet类型 ,然后设置Ws为workbook的第一个worksheet。
我们将写代码去循环Table每一列的标题来显示标题。
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
Microsoft.Office.Interop.Excel.Worksheet Ws ;
Ex.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Ws= (Microsoft.Office.Interop.Excel.Worksheet)Ex.Worksheets[1];
int Row = 0;
int Col = 0;
int i = 0;
int j = 0;
pb.Maximum = Ds.Tables[0].Rows.Count;
Row = 1;
Col = 1;
//'For Heading
lblCount.Text = "Generating Heading.";
this.Refresh();
for (i = 0; i <= Ds.Tables[0].Columns.Count - 1; i++)
{
Ws.Cells[Row, Col] = Ds.Tables[0].Columns[i].Caption;
Col += 1;
}
Row = 2;
Col = 1;
pb1.Maximum = Ds.Tables[0].Columns.Count;
lblCount.Text = "Preparing for Export Data.";
for (i = 0; i <= Ds.Tables[0].Rows.Count - 1; i++)
{
//
//FOR ALL DATA
//
pb1.Value = 0;
for (j = 0; j <= Ds.Tables[0].Columns.Count - 1; j++)
{
Ws.Cells[Row, Col] = Ds.Tables[0].Rows[i][j].ToString();
Col += 1;
pb1.Value += 1;
}
//'If data is more than 65500 then set ws to next sheet
if (Row == 65500)
{
Row = 1;
Ws = (Microsoft.Office.Interop.Excel.Worksheet)Ex.Worksheets[2];
}
Col = 1;
Row += 1;
lblCount.Text = i + 1 + " : Exported";
lblCount.Refresh();
pb.Value += 1;
}
pb.Value = 0;
Ex.Visible = true;
MessageBox.Show(Ds.Tables[0].Rows.Count + " : Records Exported. ");
Ex.Visible = true;
Ex.Quit();
Ex = null;
Ws = null;
使用StreamWriter:
这个方法比较简短而且是将数据导入如何类型的文件一种比较快方式
在这个方法中,我将使用 System.IO 命名空间,我将编程去指定的.xls 或者 .doc等扩展来直接创建一个的文件路径。
编码以文件的路径开始,这个路径是Excel文件被创建和数据存储的地方。现在,声明一个指定了路径的IO.StreamWriter对象。在这种方法中,每行的行值/列值被添加到以“|”作为分隔符的字符串中。现在,创建的文件包含以 "|" 分割的单列数据(CSV格式)。
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
//Stream Writer object to write the stream to file
StreamWriter writer = new StreamWriter(File.Create(filePath));
string str = string.Empty;
//'For Heading
lblCount.Text = "Generating Heading.";
this.Refresh();
for (int i = 0; i <= Ds.Tables[0].Columns.Count - 1; i++)
{
str += Ds.Tables[0].Columns[i].Caption +Constants.vbTab;
}
//Write stream to file adding a new line to stream
str += Microsoft.VisualBasic.Constants.vbNewLine;
writer.Write(str);
writer.Flush();
pb.Maximum = Ds.Tables[0].Rows.Count + 1;
foreach (DataRow dRow in Ds.Tables[0].Rows)
{
str = "";
for (int col = 0; col <= Ds.Tables[0].Columns.Count - 1; col++)
{
string STR1 = "";
char c = Strings.Chr(32);
//char[] sep = " ";
string[] str2 = null;
str2 = dRow[col].ToString().Split(' ');
for (int z = 0; z <= str2.Length - 1; z++)
{
//replacing all spaces and tabs with '|' (pipe sign)
string y = str2[z].ToString().Replace(Strings.Chr(32), ' ').Replace(Strings.Chr(13), ' ').Replace(Strings.Chr(10), ' ').Replace(Strings.Chr(9), ' ').Replace("|", " ");
STR1 += y + " ";
}
str += STR1 + "| ";
pb.Value += 1;
}
str += Constants.vbNewLine;
writer.Write(str);
writer.Flush();
pb.Value = 0;
}
//Close the stream writer object
writer.Close();
pb.Value = 0;
MessageBox.Show("Data Exported Successfully.");
对象拷贝的方法:
这是另外一中将数据导入Excel的方法。
在代码中,我们创建了二维数组:object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count]来包含数据表中的数据
一旦数据被存储在一个数组当中,它将通过Excel Worksheet 的get_Range().value方法 ,将数据粘贴到一个 excel worksheet 之中。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{
MessageBox.Show("There Are More than 3 data table. Data can not be exported.","提示");
return;
}
int sheetIndex = 0;
Microsoft.Office.Interop.Excel.Application Ex = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet Ws;
Microsoft.Office.Interop.Excel.Workbook Wb = Ex.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Ws = (Microsoft.Office.Interop.Excel.Worksheet)Ex.Worksheets[1];
// Copy each DataTable as a new Sheet
foreach (System.Data.DataTable dt in Ds.Tables)
{
//On Error Resume Next
int col = 0;
int row = 0;
// Copy the DataTable to an object array
object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
lblCount.Text = "Copying Columns Name.";
this.Refresh();
// Copy the column names to the first row of the object array
pb1.Maximum = dt.Columns.Count + 1;
pb1.Value = 0;
for (col = 0; col <= dt.Columns.Count - 1; col++)
{
rawData[0, col] = dt.Columns[col].ColumnName.ToUpper();
pb1.Value += 1;
}
lblCount.Text = "Copying Data";
this.Refresh();
pb1.Value = 0;
// Copy the values to the object array
pb.Maximum = dt.Rows.Count + 1;
pb.Value = 0;
for (col = 0; col <= dt.Columns.Count - 1; col++)
{
for (row = 0; row <= dt.Rows.Count - 1; row++)
{
rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
pb.Value += 1;
}
pb.Value = 0;
pb1.Value += 1;
}
pb.Value = 0;
pb1.Value = 0;
lblCount.Text = "";
this.Refresh();
// Calculate the final column letter
string finalColLetter = string.Empty;
finalColLetter = ExcelColName(dt.Columns.Count);
//Generate Excel Column Name (Column ID)
sheetIndex += 1;
Ws = (Microsoft.Office.Interop.Excel.Worksheet)Wb.Worksheets[sheetIndex];
Ws.Name = dt.TableName;
string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
Ws.get_Range(excelRange, Type.Missing).Value2 = rawData;
Ws = null;
}
Wb.SaveAs("C:\\ExportedDataUsingObjectPastingMethod.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Wb.Close(true, Type.Missing, Type.Missing);
Wb = null;
// Release the Application object
Ex.Quit();
Ex = null;
// Collect the unreferenced objects
GC.Collect();
Interaction.MsgBox("Exported Successfully.", MsgBoxStyle.Information,"提示");
我使用一个函数去找excel worksheet的列名
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{
if (Col < 0 & Col > 256)
{
Interaction.MsgBox("Invalid Argument", MsgBoxStyle.Critical,"提示");
return null;
}
int i ;
int r;
string S = null;
if (Col <= 26)
{
S = Strings.Chr(Col + 64).ToString();
}
else
{
r = (int)(Col % 26);
i = (int)System.Math.Floor((decimal)(Col / 26));
if (r == 0)
{
r = 26;
i = i - 1;
}
S = (Strings.Chr(i + 64) + Strings.Chr(r + 64)).ToString();
}
return S;
}
参考:http://www.codeproject.com/KB/vb/ExportDataToExcelFaster1.aspx
作者:朱祁林
出处:http://zhuqil.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。