直接上代码:
 try 
            {
                SaveFileDialog savefileDialog = new SaveFileDialog();
                savefileDialog.Filter = "Excel files(*.xls)|*.xls";
                savefileDialog.FilterIndex = 0;
                savefileDialog.RestoreDirectory = true;
                savefileDialog.CreatePrompt = true;
                savefileDialog.Title = "Export Excel File To";
                savefileDialog.ShowDialog();
                Stream mystream;
                mystream = savefileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(mystream, System.Text.Encoding.GetEncoding("GB2312"));
                
                string str = "";
                try
                {
                    //写标题
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            str += "\t";
                        }
                        str += dataGridView1.Columns[i].HeaderText;
                    }
                    sw.WriteLine(str);
                    //写内容
                    for (int j = 0; j < dataGridView1.Rows.Count; j++)
                    {
                        string tempStr = "";
                        for (int k = 0; k < dataGridView1.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                tempStr += "\t";
                            }
                            tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                        }
                        sw.WriteLine(tempStr);
                    }
                    sw.Close();
                    mystream.Close();
                }
                catch{}
                finally
                    {
                    sw.Close();
                    mystream.Close();
                    }
            }
            catch {}                
这个可以成功将数据导到Excel中,但当打开Excel时却提示“您尝试打开的文件‘xx.xls’的格式与文件扩展名指定的格式不一致。打开前请验证文件没有损坏且来源可信。”怎么解决。以上是将数据导入到xls中,如果我想将数据保存格式为xlsx又该怎么做?求解

解决方案 »

  1.   

    用流导入 不是真正excel格式
      

  2.   

    saveDialog.DefaultExt = "xlsx";
                saveDialog.Filter = "Excel文件|*.xlsx";
    这样可以的,
      

  3.   

    上述代码生成的文件其实是以\t和回车分割开的csv文件
    在excel2003中打开没有问题
      

  4.   

    看你系统装的office版本,03的为xls,07的为xlsx
    你可以这样写
       public static void ExcelSave (DataGridView dgv)
            { 
            if(dgv.RowCount<=1)
            {
                MessageBox.Show("缺少可以导出的数据!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
                string saveFileName=string.Empty;
                SaveFileDialog sfd=new SaveFileDialog();
                sfd.DefaultExt="xlsx";
                sfd.Filter="Excel文件|*.xlsx";
                sfd.FileName="sheet1";
                sfd.ShowDialog();
                saveFileName=sfd.FileName;
                if(saveFileName.IndexOf(".")<0)
                {
                    return;
                }
                Microsoft.Office.Interop.Excel.Application myExcelApp=new Microsoft.Office.Interop.Excel.Application();
                if(myExcelApp==null)
                {
                    MessageBox.Show("无法创建Excel,可能您未安装Excel","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }
                Microsoft.Office.Interop.Excel.Workbooks workbooks=myExcelApp.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook workbook=workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Sheets sheets=workbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet=(Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                Microsoft.Office.Interop.Excel.Range range;
                object oMis=System.Reflection.Missing.Value;
                //显示为文本格式
                range=worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[dgv.RowCount+1,dgv.ColumnCount]);
                range.NumberFormatLocal="@";
                //读入数据
                for (int i=0; i<dgv.ColumnCount;i++ )
                {
                    worksheet.Cells [1, i+1]=dgv.Columns [i].HeaderText.ToString().Trim();
                }
                for (int r=0; r<dgv.RowCount;r++ )
                {
                    for (int i=0; i<dgv.ColumnCount;i++ )
                    {
                        worksheet.Cells [r+2, i+1]=dgv.Rows [r].Cells [i].Value.ToString().Trim();
                    }
                }
                range=worksheet.get_Range( worksheet.Cells [1, 1], worksheet.Cells [dgv.RowCount+1, dgv.ColumnCount] );
                range.Columns.AutoFit();
                range.RowHeight=18;
                range.HorizontalAlignment=Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
                //保存
                if (saveFileName!=string.Empty)
                {
                    try
                    {
                        workbook.Saved=true;
                        workbook.SaveCopyAs( saveFileName );
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show( "导出文件时出错,文件可能正被打开!\n"+ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information );
                    }
                }
                else
                {
                    MessageBox.Show( "文件名不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information );
                }
                myExcelApp.Visible=false;
                myExcelApp.Quit();
                GC.Collect();//垃圾回收
            }