SQL导出数据到EXCEL的问题

时间:2021-03-22 09:39:51
DTS导出向导 不会  我这有个是用C#语言写的 

try
{
Excel.Application xApp = new Excel.ApplicationClass();
xApp.Visible = true;
//Excel.Workbook xBook = xApp.Workbooks.Add(Missing.Value);//新建一个
Excel.Workbook xBook = xApp.Workbooks._Open(@"G:\MS2004.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);//打开一个事先建好的excel 文件
for (int a = 1; a < 11; a++)
{
Excel.Worksheet sheet = (Excel.Worksheet)xBook.Worksheets[a];
sheet.Cells[1, 1] = "A";
sheet.Cells[1, 2] = "B";
sheet.Cells[1, 3] = "C";
string consql = "连接字符串";
SqlConnection myConnection = new SqlConnection(consql);
myConnection.Open();
string sql = "SELECT A,B,C FROM temp_data where(一串东西) and C='" + a+ "'";
DataSet set = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sql, myConnection);
sda.Fill(set, "temp_data");
for (int i = 1; i <= set.Tables[0].Rows.Count; i++)
{

for (int j = 0; j < set.Tables[0].Columns.Count; j++)
{
int k = i + 1;
int n = j + 1;
sheet.Cells[k, n] = set.Tables[0].Rows[i - 1][j].ToString();
}
}

}
xBook.SaveAs(@"G:\EXCEL\data.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);//另存为

xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出
xApp = null;

MessageBox.Show("导出数据成功!", "系统信息");

}

catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}

你自己好好看一下 希望对你有帮助 我以前的问题和你的差不多 把数据导入到excel中并且按照一个字段 划分sheet