DataSet导出到Excel比较完整的解决方案(一)--客户端生成文件(downmoon)

有一客户需求:

1、要从SQL Server数据库导出并生成Excel ;

2、用户下载对应的Excel并填写上传再导入到SQL server。

费了将近六个小时,故一定要把过程写下来,希望看到此文的朋友少走些不必要的弯路。

首先,想到的是直接导出到客户端,代码如下:

ContractedBlock.gif ExpandedBlockStart.gif DataSetToExcel
None.gifpublic static void DataSetToExcel(DataSet oDS, HttpResponse Response, string fileName)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
if (oDS == null || oDS.Tables[0== null || oDS.Tables[0].Rows.Count == 0dot.gifreturn; }
InBlock.gif            Response.Clear();
InBlock.gif            
//Encoding pageEncode = Encoding.GetEncoding(PageEncode);
InBlock.gif
            HttpContext.Current.Response.Charset = "gb2312";
InBlock.gif            
//Response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
InBlock.gif            
//Response.ContentType = "application/x-octet-stream";//"application/vnd.ms-excel";
InBlock.gif
            Response.ContentType = "text/csv";//"application/vnd.ms-excel";
InBlock.gif
            Response.AppendHeader("Content-Disposition""attachment;filename=" + fileName + ".cvs");
InBlock.gif            System.IO.StringWriter oSW 
= new System.IO.StringWriter();
InBlock.gif            HtmlTextWriter oHW 
= new HtmlTextWriter(oSW);
InBlock.gif            DataGrid dg 
= new DataGrid();
InBlock.gif            dg.DataSource 
= oDS.Tables[0];
InBlock.gif            dg.DataBind();
InBlock.gif            dg.RenderControl(oHW);
InBlock.gif            Response.Write(oSW.ToString());
InBlock.gif            Response.Flush();
InBlock.gif            Response.Close();
ExpandedBlockEnd.gif        }

这样生成是生成了! 客户也可以用Excel直接打开并编辑,问题来了! 上传时出错,仔细看看生成的Excel.xls,

用记事本打开,内容大致如下:

ContractedBlock.gif ExpandedBlockStart.gif Code
None.gif<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
None.gif    
<tr>
None.gif        
<td>品名</td><td>最高价格</td><td>最低价格</td><td>平均价格</td><td>计量单位</td><td>备注</td>
None.gif    
</tr><tr>
None.gif        
<td>青菜</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>南瓜</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>瓠子</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>冬春笋</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>雪里蕻</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>樱桃萝卜</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>佛手瓜</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>白菜鼎</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td></td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>食用菌</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr><tr>
None.gif        
<td>黄瓜</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>元/公斤</td><td>&nbsp;</td>
None.gif    
</tr>
None.gif
</table>

 原来,就是纯粹的html格式,披了件Excel的外衣。这样用户传上来的文件当然不是标准的Excel格式了!

于是, 想到直接生成xml格式的Excel文档,方法如下 :

ContractedBlock.gif ExpandedBlockStart.gif ExportToExcel
ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
InBlock.gif        
/// 执行导出
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="ds">要导出的DataSet</param>
ExpandedBlockEnd.gif        
/// <param name="strExcelFileName">要导出的文件名</param>

None.gif        public static void ExportToExcel(DataSet source, string fileName)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif
InBlock.gif            System.IO.StreamWriter excelDoc;
InBlock.gif
InBlock.gif            excelDoc 
= new System.IO.StreamWriter(fileName);
InBlock.gif            
const string startExcelXML = "<xml version>\r\n<Workbook " +
InBlock.gif                  
"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
InBlock.gif                  
" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
InBlock.gif                  
"xmlns:x=\"urn:schemas-    microsoft-com:office:" +
InBlock.gif
                  "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
InBlock.gif                  
"office:spreadsheet\">\r\n <Styles>\r\n " +
InBlock.gif
                  "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
InBlock.gif                  
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
InBlock.gif                  
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
InBlock.gif                  
"\r\n <Protection/>\r\n </Style>\r\n " +
InBlock.gif                  
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
InBlock.gif                  
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
InBlock.gif                  
"<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
InBlock.gif                  
" ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
InBlock.gif                  
"ss:ID=\"Decimal\">\r\n <NumberFormat " +
InBlock.gif                  
"ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
InBlock.gif                  
"<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
InBlock.gif                  
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
InBlock.gif                  
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
InBlock.gif                  
"ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
InBlock.gif                  
"</Styles>\r\n ";
InBlock.gif            
const string endExcelXML = "</Workbook>";
InBlock.gif
InBlock.gif            
int rowCount = 0;
InBlock.gif            
int sheetCount = 1;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
/**//*
InBlock.gif           <xml version>
InBlock.gif           <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
InBlock.gif           xmlns:o="urn:schemas-microsoft-com:office:office"
InBlock.gif           xmlns:x="urn:schemas-microsoft-com:office:excel"
InBlock.gif           xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
InBlock.gif           <Styles>
InBlock.gif           <Style ss:ID="Default" ss:Name="Normal">
InBlock.gif             <Alignment ss:Vertical="Bottom"/>
InBlock.gif             <Borders/>
InBlock.gif             <Font/>
InBlock.gif             <Interior/>
InBlock.gif             <NumberFormat/>
InBlock.gif             <Protection/>
InBlock.gif           </Style>
InBlock.gif           <Style ss:ID="BoldColumn">
InBlock.gif             <Font x:Family="Swiss" ss:Bold="1"/>
InBlock.gif           </Style>
InBlock.gif           <Style ss:ID="StringLiteral">
InBlock.gif             <NumberFormat ss:Format="@"/>
InBlock.gif           </Style>
InBlock.gif           <Style ss:ID="Decimal">
InBlock.gif             <NumberFormat ss:Format="0.0000"/>
InBlock.gif           </Style>
InBlock.gif           <Style ss:ID="Integer">
InBlock.gif             <NumberFormat ss:Format="0"/>
InBlock.gif           </Style>
InBlock.gif           <Style ss:ID="DateLiteral">
InBlock.gif             <NumberFormat ss:Format="mm/dd/yyyy;@"/>
InBlock.gif           </Style>
InBlock.gif           </Styles>
InBlock.gif           <Worksheet ss:Name="Sheet1">
InBlock.gif           </Worksheet>
InBlock.gif           </Workbook>
ExpandedSubBlockEnd.gif           
*/

InBlock.gif            excelDoc.Write(startExcelXML);
InBlock.gif            excelDoc.Write(
"<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
InBlock.gif            excelDoc.Write(
"<Table>");
InBlock.gif            excelDoc.Write(
"<Row>");
InBlock.gif            
for (int x = 0; x < source.Tables[0].Columns.Count; x++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                excelDoc.Write(
"<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
InBlock.gif                excelDoc.Write(source.Tables[
0].Columns[x].ColumnName);
InBlock.gif                excelDoc.Write(
"</Data></Cell>");
ExpandedSubBlockEnd.gif            }

InBlock.gif            excelDoc.Write(
"</Row>");
InBlock.gif            
foreach (DataRow x in source.Tables[0].Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                rowCount
++;
InBlock.gif                
//if the number of rows is > 64000 create a new page to continue output
InBlock.gif

InBlock.gif                
if (rowCount == 64000)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    rowCount 
= 0;
InBlock.gif                    sheetCount
++;
InBlock.gif                    excelDoc.Write(
"</Table>");
InBlock.gif                    excelDoc.Write(
" </Worksheet>");
InBlock.gif                    excelDoc.Write(
"<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
InBlock.gif                    excelDoc.Write(
"<Table>");
ExpandedSubBlockEnd.gif                }

InBlock.gif                excelDoc.Write(
"<Row>"); //ID=" + rowCount + "
InBlock.gif

InBlock.gif                
for (int y = 0; y < source.Tables[0].Columns.Count; y++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    System.Type rowType;
InBlock.gif                    rowType 
= x[y].GetType();
InBlock.gif                    
switch (rowType.ToString())
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
case "System.String":
InBlock.gif                            
string XMLstring = x[y].ToString();
InBlock.gif                            XMLstring 
= XMLstring.Trim();
InBlock.gif                            XMLstring 
= XMLstring.Replace("&""&");
InBlock.gif                            XMLstring 
= XMLstring.Replace(">"">");
InBlock.gif                            XMLstring 
= XMLstring.Replace("<""<");
InBlock.gif                            excelDoc.Write(
"<Cell ss:StyleID=\"StringLiteral\">" +
InBlock.gif                                           
"<Data ss:Type=\"String\">");
InBlock.gif                            excelDoc.Write(XMLstring);
InBlock.gif                            excelDoc.Write(
"</Data></Cell>");
InBlock.gif                            
break;
InBlock.gif                        
case "System.DateTime":
InBlock.gif                            
//Excel has a specific Date Format of YYYY-MM-DD followed by  
InBlock.gif
InBlock.gif                            
//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
InBlock.gif
InBlock.gif                            
//The Following Code puts the date stored in XMLDate 
InBlock.gif
InBlock.gif                            
//to the format above
InBlock.gif

InBlock.gif                            DateTime XMLDate 
= (DateTime)x[y];
InBlock.gif                            
string XMLDatetoString = ""//Excel Converted Date
InBlock.gif

InBlock.gif                            XMLDatetoString 
= XMLDate.Year.ToString() +
InBlock.gif                                 
"-" +
InBlock.gif                                 (XMLDate.Month 
< 10 ? "0" +
InBlock.gif                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) 
+
InBlock.gif                                 
"-" +
InBlock.gif                                 (XMLDate.Day 
< 10 ? "0" +
InBlock.gif                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) 
+
InBlock.gif                                 
"T" +
InBlock.gif                                 (XMLDate.Hour 
< 10 ? "0" +
InBlock.gif                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) 
+
InBlock.gif                                 
":" +
InBlock.gif                                 (XMLDate.Minute 
< 10 ? "0" +
InBlock.gif                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) 
+
InBlock.gif                                 
":" +
InBlock.gif                                 (XMLDate.Second 
< 10 ? "0" +
InBlock.gif                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) 
+
InBlock.gif                                 
".000";
InBlock.gif                            excelDoc.Write(
"<Cell ss:StyleID=\"DateLiteral\">" +
InBlock.gif                                         
"<Data ss:Type=\"DateTime\">");
InBlock.gif                            excelDoc.Write(XMLDatetoString);
InBlock.gif                            excelDoc.Write(
"</Data></Cell>");
InBlock.gif                            
break;
InBlock.gif                        
case "System.Boolean":
InBlock.gif                            excelDoc.Write(
"<Cell ss:StyleID=\"StringLiteral\">" +
InBlock.gif                                        
"<Data ss:Type=\"String\">");
InBlock.gif                            excelDoc.Write(x[y].ToString());
InBlock.gif                            excelDoc.Write(
"</Data></Cell>");
InBlock.gif                            
break;
InBlock.gif                        
case "System.Int16":
InBlock.gif                        
case "System.Int32":
InBlock.gif                        
case "System.Int64":
InBlock.gif                        
case "System.Byte":
InBlock.gif                            excelDoc.Write(
"<Cell ss:StyleID=\"Integer\">" +
InBlock.gif                                    
"<Data ss:Type=\"Number\">");
InBlock.gif                            excelDoc.Write(x[y].ToString());
InBlock.gif                            excelDoc.Write(
"</Data></Cell>");
InBlock.gif                            
break;
InBlock.gif                        
case "System.Decimal":
InBlock.gif                        
case "System.Double":
InBlock.gif                            excelDoc.Write(
"<Cell ss:StyleID=\"Decimal\">" +
InBlock.gif                                  
"<Data ss:Type=\"Number\">");
InBlock.gif                            excelDoc.Write(x[y].ToString());
InBlock.gif                            excelDoc.Write(
"</Data></Cell>");
InBlock.gif                            
break;
InBlock.gif                        
case "System.DBNull":
InBlock.gif                            excelDoc.Write(
"<Cell ss:StyleID=\"StringLiteral\">" +
InBlock.gif                                  
"<Data ss:Type=\"String\">");
InBlock.gif                            excelDoc.Write(
"");
InBlock.gif                            excelDoc.Write(
"</Data></Cell>");
InBlock.gif                            
break;
InBlock.gif                        
default:
InBlock.gif                            
throw (new Exception(rowType.ToString() + " not handled."));
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                excelDoc.Write(
"</Row>");
ExpandedSubBlockEnd.gif            }

InBlock.gif            excelDoc.Write(
"</Table>");
InBlock.gif            excelDoc.Write(
" </Worksheet>");
InBlock.gif            excelDoc.Write(endExcelXML);
InBlock.gif            excelDoc.Close();
ExpandedBlockEnd.gif        }

可惜, 生成的倒是XML格式了,但还是上传格式不正确,考虑到客户端可能是Excel2007/2003-97等等,决定放弃保存Excel到客户端的方式。

 第三种尝试方案:用cvs保存,将第一种方法改为:

ContractedBlock.gif ExpandedBlockStart.gif ExportToCVS
None.gif  Response.ContentType = "text/csv";//"application/vnd.ms-excel";
None.gif
            Response.AppendHeader("Content-Disposition""attachment;filename=" + fileName + ".cvs");

 生成格式大致如下:

ContractedBlock.gif ExpandedBlockStart.gif CVS格式
None.gif"品名","最高价格","最低价格","平均价格","计量单位","备注"
None.gif"青菜","","","","元/公斤",""
None.gif"南瓜","","","","元/公斤",""
None.gif"瓠子","","","","元/公斤",""
None.gif"冬春笋","","","","元/公斤",""
None.gif"雪里蕻","","","","元/公斤",""
None.gif"樱桃萝卜","","","","元/公斤",""
None.gif"佛手瓜","","","","元/公斤",""
None.gif"白菜鼎","","","","元/公斤",""
None.gif"蒜","","","","元/公斤",""
None.gif"食用菌","","","","元/公斤",""
None.gif"黄瓜","","","","元/公斤",""

导入到SQL Server时有多种方法:

给出简要代码:

ContractedBlock.gif ExpandedBlockStart.gif GetDataFromCSV
None.gif public static DataTable GetDataFromCSV(string filePath,int beginColumn)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
int intColCount = 0;
InBlock.gif            
bool blnFlag = true;
InBlock.gif            DataTable mydt 
= new DataTable("myTableName");
InBlock.gif
InBlock.gif            DataColumn mydc;
InBlock.gif            DataRow mydr;
InBlock.gif
InBlock.gif           
InBlock.gif            
string strline;
InBlock.gif            
string[] aryline;
InBlock.gif
InBlock.gif            System.IO.StreamReader mysr 
= new System.IO.StreamReader(filePath,System.Text.Encoding.UTF8);
InBlock.gif            
int FlagFirst =1;
InBlock.gif            
while ((strline = mysr.ReadLine()) != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//if (beginColumn == FlagFirst) { FlagFirst++; continue; }
InBlock.gif
                strline = strline.Replace("\n""");
InBlock.gif                strline 
= strline.Replace("\r""");
InBlock.gif                strline 
= strline.Replace("\t""");
InBlock.gif                
//aryline = strline.Split(new char[] { '|' });
ExpandedSubBlockStart.gifContractedSubBlock.gif
                aryline = strline.Split(new char[] dot.gif',' });
InBlock.gif
InBlock.gif                
if (blnFlag)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    blnFlag 
= false;
InBlock.gif                    intColCount 
= aryline.Length;
InBlock.gif                    
for (int i = 0; i < aryline.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        mydc 
= new DataColumn(aryline[i]);
InBlock.gif                        mydt.Columns.Add(mydc);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                mydr 
= mydt.NewRow();
InBlock.gif                
for (int i = 0; i < intColCount; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    mydr[i] 
= aryline[i];
ExpandedSubBlockEnd.gif                }

InBlock.gif                mydt.Rows.Add(mydr);
InBlock.gif                FlagFirst
++;
ExpandedSubBlockEnd.gif            }

InBlock.gif 
InBlock.gif            mysr.Close();
InBlock.gif            mysr.Dispose();
InBlock.gif            
return mydt;
ExpandedBlockEnd.gif        }

 也有人给出方案,直接从cvs中读取

ContractedBlock.gif ExpandedBlockStart.gif GetDataSetFromCSV
None.gif public static string PreFilePath=@"c:\Excel\";
None.gif        
public static string strconn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+PreFilePath+";Extensions=asc,csv,tab,txt;";
None.gif        
public static DataSet GetDataSetFromCSV( string filename)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            OdbcConnection objconn 
= new OdbcConnection(strconn);
InBlock.gif            DataSet dscsv 
= new DataSet();
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string strsql = "select * from " + filename;                     //filename, for example: 1.csv
InBlock.gif
                OdbcDataAdapter odbccsvdataadapter = new OdbcDataAdapter(strsql, objconn);
InBlock.gif
InBlock.gif                odbccsvdataadapter.Fill(dscsv);
InBlock.gif                
return dscsv;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw ex;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

 尝试失败!!

 Code Project 上有篇文章,

A Fast CSV Reader

也可以试试。

 虽然也可以凑合用, 但总觉得CVS出错的可能性更大。

 到此,决定放弃客户端生成的方式,请看下篇

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值