读书人

girdview导出到EXCEL方法!

发布时间: 2012-04-14 17:14:21 作者: rapoo

girdview导出到EXCEL方法在线等!!!!
girdview导出到EXCEL方法,不要HttpResponse导出的,要EXCEL的API导出的标准格式!谢谢各位

[解决办法]

C# code
public static void ToExcel(DataGridView dgv, string name)        {            try            {                //总可见列数,总可见行数                int colCount = dgv.Columns.GetColumnCount(DataGridViewElementStates.Visible);                int rowCount = dgv.Rows.GetRowCount(DataGridViewElementStates.Visible);                //dataGridView 没有数据提示                if (dgv.Rows.Count == 0 || rowCount == 0)                {                    MessageBox.Show("列表中没有数据无法导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);                    return;                }                SaveFileDialog save = new SaveFileDialog();                save.Filter = "excel files(*.xls)|*.xls";                save.Title = "请选择要导出数据的位置";                save.FileName = name + DateTime.Now.ToLongDateString();                save.InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);                if (save.ShowDialog() == DialogResult.OK)                {                    XlsDocument xls = new XlsDocument();//创建空xls文档                    xls.FileName = save.FileName;//保存路径,如果直接发送到客户端的话只需要名称 生成名称                    Worksheet sheet = xls.Workbook.Worksheets.Add(name); //创建一个工作页为Dome                              //设置文档列属性                     ColumnInfo cinfo = new ColumnInfo(xls, sheet);//设置xls文档的指定工作页的列属性                    cinfo.Collapsed = true;                    //设置列的范围 如 0列-10列                    cinfo.ColumnIndexStart = 0;//列开始                    cinfo.ColumnIndexEnd = 10;//列结束                    cinfo.Collapsed = true;                    cinfo.Width = 90 * 60;//列宽度                    sheet.AddColumnInfo(cinfo);                    //设置文档列属性结束                    //设置指定工作页跨行跨列                    MergeArea ma = new MergeArea(1, 1, 1, dgv.ColumnCount);//从第1行跨到第二行,从第一列跨到第5列                    sheet.AddMergeArea(ma);                    //设置指定工作页跨行跨列结束                    //创建列样式创建列时引用                    XF cellXF = xls.NewXF();                    cellXF.VerticalAlignment = VerticalAlignments.Centered;                    cellXF.HorizontalAlignment = HorizontalAlignments.Centered;                    cellXF.Font.Height = 24 * 12;                    cellXF.Font.Bold = true;                    cellXF.Pattern = 0;//设定单元格填充风格。如果设定为0,则是纯色填充                    cellXF.PatternBackgroundColor = Colors.Black;//填充的背景底色                    cellXF.PatternColor = Colors.Black;//设定填充线条的颜色                    //创建列样式结束                    //创建列                    Cells cells = sheet.Cells; //获得指定工作页列集合                    //列操作基本                    Cell cell = cells.Add(1, 1, name, cellXF);//添加标题列返回一个列  参数:行 列 名称 样式对象                    //设置XY居中                    cell.HorizontalAlignment = HorizontalAlignments.Centered;                    cell.VerticalAlignment = VerticalAlignments.Centered;                    //设置字体                    cell.Font.Bold = true;//设置粗体                    cell.Font.ColorIndex = 0;//设置颜色码                               cell.Font.FontFamily = FontFamilies.Roman;//设置字体 默认为宋体                                   //创建列结束                      //生成字段名称                    int k = 0;                    for (int i = 0; i < dgv.ColumnCount; i++)                    {                        if (dgv.Columns[i].Visible)  //不导出隐藏的列                        {                            Cell title = cells.Add(2, k + 1, dgv.Columns[i].HeaderText);                            title.HorizontalAlignment = HorizontalAlignments.Centered;                            title.VerticalAlignment = VerticalAlignments.Centered;                            k++;                        }                    }                    //填充数据                    for (int i = 0; i < dgv.RowCount; i++)                    {                        k = 1;                        for (int j = 0; j < dgv.ColumnCount; j++)                        {                            if (dgv.Columns[j].Visible)  //不导出隐藏的列                            {                                if (dgv[j, i].ValueType == typeof(string))                                {                                    //excel.Cells[i + 2, k] = "" + dgv[j, i].Value.ToString();                                    cells.Add(i + 3, k, "" + dgv[j, i].Value.ToString());                                }                                else                                {                                    cells.Add(i + 3, k, dgv[j, i].Value.ToString());                                }                            }                            k++;                        }                    }                    xls.Save(true);//保存                    MessageBox.Show("Excel文件导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                }            }            catch (Exception ce)            {                MessageBox.Show(ce.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);            }        } 


[解决办法]
private void btnCSV_Click(object sender, EventArgs e)
{
//C#创建Excel文件之取得数据
DataTable dt = GetData();
ComLibrary com = new ComLibrary();
if (dt != null)
{
SaveExcel(dt);
}
}
/// <summary>
/// 创建Excel
/// </summary>
private void SaveExcel(DataTable dt)
{
//创建一个excel application
Microsoft.Office.Interop.Excel.Application xls_exp = null;
int rowindex = 1;
int colindex = 0;
string path = "";
//创建一个workbook,一个worksheet
Microsoft.Office.Interop.Excel.Workbook xls_book = null;
Microsoft.Office.Interop.Excel.Worksheet xls_sheet = null;
try
{
this.Cursor = Cursors.WaitCursor;
xls_exp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xls_book = xls_exp.Workbooks.Add(true);
//同样方法处理数据
int rowidx = 0;
foreach (DataRow row in dt.Rows)
{
//首行
if (rowidx == 0)
{
colindex = 1;
xls_sheet = (Microsoft.Office.Interop.Excel.Worksheet)xls_book.ActiveSheet;
//xls_sheet.Name = "测试";
if (row["TRADEMARK"].ToString() == "")
{
xls_sheet.Name = "任意";
}
else
{
xls_sheet.Name = row["TRADEMARK"].ToString();
}
xls_exp.Cells[1, colindex] = "编号";
xls_exp.Cells[1, colindex + 1] = "名称";
xls_exp.Cells[1, colindex + 2] = "数量";
xls_exp.Cells[1, colindex + 3] = "随便";
}
else
{
if (row["TRADEMARK"].ToString() != dt.Rows[rowidx - 1]["TRADEMARK"].ToString())
{
rowindex = 1;
xls_exp.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xls_sheet = (Microsoft.Office.Interop.Excel.Worksheet)xls_book.Worksheets[1];
//xls_sheet.Name = row["TRADEMARK"].ToString();
if (row["TRADEMARK"].ToString() == "")
{
xls_sheet.Name = "随便";
}
else
{
xls_sheet.Name = row["TRADEMARK"].ToString();
}
colindex = 1;
xls_exp.Cells[1, colindex] = "编号";
xls_exp.Cells[1, colindex + 1] = "名称";
xls_exp.Cells[1, colindex + 2] = "数量";
xls_exp.Cells[1, colindex + 3] = "随便啥";
}
}
colindex = 1;
////数字格式设置为文本
//xls_sheet.get_Range(
//xls_exp.Cells[rowindex-1, colindex],
//xls_exp.Cells[rowindex-1, colindex + 3]).NumberFormatLocal = "@";

rowindex++;
//C#创建Excel文件之给cell赋值
//数字格式设置为文本
xls_sheet.get_Range(xls_exp.Cells[rowindex, colindex], xls_exp.Cells[rowindex, colindex + 1]).NumberFormatLocal = "@";
xls_exp.Cells[rowindex, colindex] = row["ITEMCD"] ;
xls_exp.Cells[rowindex, colindex + 1] = row["ITEMNAME"];
xls_exp.Cells[rowindex, colindex + 2] = row["SALEQTY"];
xls_exp.Cells[rowindex, colindex + 3] = row["QTY"];
rowidx++;
}
this.Cursor = Cursors.Default;

string filename;
if (ComLibrary.GetRadioButton(pnlList) == "4")//其他报表
{
if (ComLibrary.ToInt(dtpStartDate.txtDate.Text) != ComLibrary.ToInt(dtpEndDate.txtDate.Text))
{
filename = (ComLibrary.ToInt(dtpStartDate.txtDate.Text)).ToString("####年##月##日")
+ (ComLibrary.ToInt(dtpEndDate.txtDate.Text)).ToString(" 至 ####年##月##日报表") + ".xls";


}
else
{//考虑到可以打印过去某日的报表
filename = (ComLibrary.ToInt(dtpEndDate.txtDate.Text)).ToString("####年##月##报表") + ".xls";
}
}
else
{
filename = DateTime.Now.ToString("yyyy年MM月dd日") + "某.xls";
}
saveFileDialog1.FileName = filename;
//saveFileDialog1.Filter = "Excel文档|.xls";
saveFileDialog1.Title = "存放位置";
saveFileDialog1.Filter = "excel files(*.xls)|*.xls";//excel files(*.xls)|*.xls|All files(*.*)|*.*
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
path = saveFileDialog1.FileName;
//放弃保存
this.Cursor = Cursors.Default;
//不替换时关闭
xls_book.Close(false, path, Missing.Value);//关闭不保存修改
xls_exp.Application.Quit();
xls_exp.Quit();
GC.Collect();
return;
}
path = saveFileDialog1.FileName;
xls_exp.Cells.EntireColumn.AutoFit();
xls_book.Saved = true;
xls_book.SaveCopyAs(path);
DialogResult dr = MessageBox.Show("导出成功!是否打开所在文件夹?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
System.Diagnostics.Process.Start("explorer.exe", "/select," + path);
}
this.Cursor = Cursors.Default;

xls_book.Close(false, path, Missing.Value);//关闭不保存修改
xls_exp.Application.Quit();
xls_exp.Quit();
GC.Collect();
}
catch (Exception err)
{
//异常时关闭
xls_book.Close(false, path, Missing.Value);//关闭不保存修改
xls_exp.Application.Quit();
xls_exp.Quit();
GC.Collect();
MessageBox.Show("保存失败!(" + err.ToString() + ")", "系统信息",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
this.Cursor = Cursors.Default;
}
}
[解决办法]
http://topic.csdn.net/u/20100908/21/566e79b3-46ea-4244-9da2-dab181c6db54.html
[解决办法]
用控件吧,在是免了






my blog
http://ufo-crackerx.blog.163.com/

读书人网 >C#

热点推荐