日期:2014-05-18  浏览次数:20879 次

C# 将dataset里面的数据导入到excel 谢谢!!!
我有一个dataset里面 里面肯能有table0,table1,talble2......
我需要把这个数据分别保存到excel里面的sheet1,sheet2,sheet3.....里面去,
需要怎么做?请高手赐教!请给出代码提示!谢谢!

------解决方案--------------------
用ado.net,把excel作为一个数据库写入,
------解决方案--------------------
连接字符串:
String strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strExcelFilename+";" + "Extended Properties=Excel 8.0;";

用sql语句create table创建sheet:
"CREATE TABLE TestSheet ([ID] INTEGER,[Username] VarChar,[UserPwd] VarChar)";

然后插入就是普通的insert into语句了,

------解决方案--------------------
table循环对应sheet

for(int i=0;i<dataSet.Tables.Count;i++)
{
//根据i索引导入excel
}
------解决方案--------------------
protected void AddExcel(DataSet ds, ref bool s)
{
try
{
System.Data.DataTable dt = ds.Tables[0];

// string fileName ="C:\\数据处理文件夹\\"+ Guid.NewGuid() + ".xls";
//string str = DateTime.Now.ToShortDateString();
// string[] strar=str.Split(' ');
// string str1 =strar[0]+strar[1]; 
SaveFileDialog sf = new SaveFileDialog();
sf.InitialDirectory = "C:\\";
sf.Filter = "excel文件(*.xls)|*.xls";

if (sf.ShowDialog()==DialogResult.OK)
{
string fileName = sf.FileName; //"C:\\数据处理文件夹\\" +str+ ".xls";
Excel.Application excel = new Excel.ApplicationClass();

int rowIndex = 1;
int colIndex = 0;

excel.Application.Workbooks.Add(true);

foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}

foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
{
excel.Cells[rowIndex, colIndex + 1] = row[colIndex].ToString();
}
}

excel.Visible = false;
// excel.ActiveWorkbook.s
excel.ActiveWorkbook.SaveAs(fileName, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
//excel.Save(fileName); 

excel.Quit();
excel = null;

GC.Collect();//垃圾回收
}
}
catch
{
s = false;
}
// }

}
------解决方案--------------------
/// <summary>
/// DataTable直接导出Excel,此方法会把DataTable的数据用Excel打开,再自己手动去保存到确切的位置
/// </summary>
/// <param name="dt">要导出Excel的DataTable</param>
/// <returns></returns>
public static void ExportExcel(System.Data.DataTable table, string savePath, bool isExit)
{
if (!isExit)//保存路径是否存在
File.Copy(System.Windows.Forms.Application.StartupPath + @"\Excel\Excel.xls", savePath);
_Excel.Application app = new _Excel.ApplicationClass();