日期:2014-05-17  浏览次数:20802 次

winform导出Excel
将Winform的表单导入到Excel。

界面类似于移动缴费单的形式,要整体导入。

------解决方案--------------------
C# code
protected void AddExcel(DataSet ds)  
{
DataTable dt = ds.Tables[0];

string fileName = Guid.NewGuid() + ".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.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();//垃圾回收
}

------解决方案--------------------
这个是导出DataSet到Excel的,改造一下,就可以了。
1.引用 COM组件 Excel.dll 

2.实现如下 

public void ExportExcel(){ 
DataSet ds=this.DataSet;//取得dataGrid绑定的DataSet 
if(ds==null) return; 

string saveFileName=""; 
bool fileSaved=false; 
SaveFileDialog saveDialog=new SaveFileDialog(); 
saveDialog.DefaultExt ="xls"; 
saveDialog.Filter="Excel文件|*.xls"; 
saveDialog.FileName ="Sheet1"; 
saveDialog.ShowDialog(); 
saveFileName=saveDialog.FileName; 
if(saveFileName.IndexOf(":")<0) return; //被点了取消 

Excel.Application xlApp=new Excel.Application(); 

if(xlApp==null){ 
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel"); 
return; 


Excel.Workbooks workbooks=xlApp.Workbooks; 
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); 
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
Excel.Range range; 

string oldCaption=this.CaptionText; 
long totalCount=ds.Tables[0].Rows.Count; 
long rowRead=0; 
float percent=0; 

worksheet.Cells[1,1]=this.CaptionText; 
//写入字段 
for(int i=0;i<ds.Tables[0].Columns.Count;i++){ 
worksheet.Cells[2,i+1]=ds.Tables[0].Columns[i].ColumnName; 
range=(Excel.Range)worksheet.Cells[2,i+1]; 
range.Interior.ColorIndex = 15; 
range.Font.Bold = true; 


//写入数值 
this.CaptionVisible = true; 
for(int r=0;r<ds.Tables[0].Rows.Count;r++){ 
for(int i=0;i<ds.Tables[0].Columns.Count;i++){ 
worksheet.Cells[r+3,i+1]=ds.Tables[0].Rows[r][i]; 

rowRead++; 
percent=((float)(100*rowRead))/totalCount; 
this.CaptionText = "正在导出数据["+ percent.ToString("0.00") +"%]..."; 
Application.DoEvents(); 

this.CaptionVisible = false; 
this.CaptionText = oldCaption; 

range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds.Tables[0].Rows.Count+2,ds.Tables[0].Columns.Count]); 
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null); 

range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorInde