返回> 网站首页 

基于asp.net的Excel、Word操作

yoours2014-04-23 11:19:40 阅读 1326

简介一边听听音乐,一边写写文章。

 C# Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dtTemp"></param>
/// <param name="ServerPath"></param>
/// <param name="TextName"></param>
/// <param name="fc">将number格式化成string</param>
public static void ExportTasks(System.Data.DataTable dtTemp,string ServerPath,string TextName,int fc,string sName)
{
    // 定义要使用的Excel 组件接口
    // 定义Application 对象,此对象表示整个Excel 程序
    Application excelApp = null;
    // 定义Workbook对象,此对象代表工作薄
    Workbook workBook;
    // 定义Worksheet 对象,此对象表示Execel 中的一张工作表
    Worksheet ws = null;
    //定义Range对象,此对象代表单元格区域
    Range range;

    int dcell = 1;
    int rowindex = 0int colindex = 0;

    int rowcount = dtTemp.Rows.Count;
    int colcount = dtTemp.Columns.Count;
    try
    {
        //初始化 Application 对象 excelApp
        excelApp = new Application();
        //在工作薄的第一个工作表上创建任务列表
        workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        ws = (Worksheet)workBook.Worksheets[1];

        // 命名工作表的名称为
        ws.Name = !string.IsNullOrEmpty(sName) ? sName : "Sheet1" ;
        //创建缓存
        Object[,] objdata = new object[rowcount + 1, colcount];

        //创建标题
        foreach (System.Data.DataColumn dc in dtTemp.Columns)
        {
            objdata[rowindex, colindex++] = dc.ColumnName;
        }
        //获取数据
        for (int i = 0; i < rowcount; i++)
        {
            dcell = 0;
            for (int j = 0; j < colcount; j++)
            {
                objdata[i + 1, dcell++] = dtTemp.Rows[i][dtTemp.Columns[j].ColumnName].ToString();
            }
        }
        //写入Excel            
        range = ws.get_Range(excelApp.Cells[11], excelApp.Cells[rowcount + 1, colcount]);
        //range.NumberFormatLocal = "@";//所有字段格式化为文本格式
        ws.get_Range(excelApp.Cells[2, fc], excelApp.Cells[rowcount + 1, fc]).NumberFormatLocal = "@";
        range.Value2 = objdata;
        System.Windows.Forms.Application.DoEvents();
        //设置格式
        range = ws.get_Range(excelApp.Cells[11], excelApp.Cells[1, colcount]);
        range.Font.Bold = true;//标题粗体

        excelApp.Cells.HorizontalAlignment = Constants.xlCenter; //全局左对齐
        excelApp.Cells.EntireColumn.AutoFit();
        range = ws.get_Range(excelApp.Cells[11], excelApp.Cells[rowcount + 1, colcount]);
        range.Borders.LineStyle = 1;
        //range.Font.Bold = true; //标题粗体
        //显示 Excel
        //excelApp.Visible = true;                
        workBook.SaveCopyAs(ServerPath.Replace("//""\\") + TextName + ".xls");
        workBook.Close(falsenullnull);
        excelApp.Quit();
        ws = null;
    }
    catch (Exception ex)
    {
        WriteLog.SetErrorMsg("ExportTasks""", ex.Message);   //处理错误               
        excelApp.Quit();
        throw ex;
    }
}

/// <summary>
/// 导出Excel 
/// </summary>
/// <param name="dtTemp"></param>
public static void ExportCMB(System.Data.DataTable dtTemp, string ServerPath, string TextName)
{
    // 定义要使用的Excel 组件接口
    // 定义Application 对象,此对象表示整个Excel 程序
    Application excelApp = null;
    // 定义Workbook对象,此对象代表工作薄
    Workbook workBook;
    // 定义Worksheet 对象,此对象表示Execel 中的一张工作表
    Worksheet ws = null;
    //定义Range对象,此对象代表单元格区域
    Range range;

    int dcell = 1;           
    int colindex = 0;

    int rowcount = dtTemp.Rows.Count;
    int colcount = 14;
    try
    {
        //初始化 Application 对象 excelApp
        excelApp = new Application();
        //在工作薄的第一个工作表上创建任务列表
        workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        ws = (Worksheet)workBook.Worksheets[1];

        // 命名工作表的名称为
        ws.Name = "Sheet1";
        //创建缓存
        Object[,] objdata = new object[rowcount + 3, colcount];
        objdata[00] = "代发工资表";
        objdata[10] = "TF:QY1CWS1";
        //创建标题
        foreach (System.Data.DataColumn dc in dtTemp.Columns)
        {
            objdata[2, colindex++] = dc.ColumnName;
        }
        //获取数据
        for (int i = 0; i < rowcount; i++)
        {
            dcell = 0;
            for (int j = 0; j < colcount; j++)
            {
                objdata[i + 3, dcell++] = dtTemp.Rows[i][dtTemp.Columns[j].ColumnName].ToString();
            }
        }
        //写入Excel            
        range = ws.get_Range(excelApp.Cells[11], excelApp.Cells[rowcount + 3, colcount]);
        ws.get_Range(excelApp.Cells[412], excelApp.Cells[rowcount + 312]).NumberFormatLocal = "@";
        //range.NumberFormatLocal = "@";                
        range.Value2 = objdata;
        range.Font.Size = 10;
        System.Windows.Forms.Application.DoEvents();
        //设置格式
        excelApp.Cells.HorizontalAlignment = Constants.xlLeft; //全局左对齐
        excelApp.Cells.EntireColumn.AutoFit();
        range = ws.get_Range(excelApp.Cells[31], excelApp.Cells[rowcount + 3, colcount]);
        //range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
        range.Borders.LineStyle = 1;
        //显示 Excel
        //excelApp.Visible = true;
        workBook.SaveCopyAs(ServerPath.Replace("//""\\") + TextName + ".xls");
        workBook.Close(falsenullnull);
        excelApp.Quit();
        ws = null;
    }
    catch (Exception ex)
    {
        WriteLog.SetErrorMsg("ExportICBC""", ex.Message);   //处理错误               
        excelApp.Quit();
        throw ex;
    }
}

// 导出Word
public static void ExportToWord(DataGridView dgv, ProgressBar progress, SaveFileDialog savefile)
{
    Microsoft.Office.Interop.Word.Document WordDoc = new Microsoft.Office.Interop.Word.Document();
    Microsoft.Office.Interop.Word.Table WordTable;
    object WordObj;
    if (dgv.Rows.Count == 0)
    {
        return;
    }else{
        savefile.AddExtension = true;
        savefile.DefaultExt = ".doc";
        savefile.CreatePrompt = true;
        savefile.Title = "导出文件保存路径";
        savefile.Filter = "Word files (*.doc)|*.doc";
        if (savefile.ShowDialog() == DialogResult.OK)
        {
            progress.Visible = true;
            object path = savefile.FileName;
            WordObj = System.Reflection.Missing.Value;
            //建立word对象
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            WordDoc = word.Documents.Add(ref WordObj, ref WordObj, ref WordObj, ref WordObj);
            //建立表格
            //将数据生成word表格文件
            WordTable = WordDoc.Tables.Add(WordDoc.Paragraphs.Last.Range, dgv.RowCount, dgv.ColumnCount, ref WordObj, ref WordObj);
            WordTable.Columns.SetWidth(50, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustNone);

            try
            {
                for (int i = 0; i < dgv.Columns.Count; i++)//设置标题
                {
                    WordTable.Cell(0, i + 1).Range.Text = dgv.Columns[i].HeaderText;
                    WordTable.Cell(0, i + 1).Range.Font.Size = 5;
                }
                for (int i = 1; i < dgv.Rows.Count; i++)//填充数据
                {
                    for (int j = 0; j < dgv.Columns.Count; j++)
                    {
                        WordTable.Cell(i + 1, j + 1).Range.Text = dgv[j, i - 1].Value.ToString();
                        WordTable.Cell(i+1, j + 1).Range.Font.Size = 5;
                    }
                    progress.Value += 100 / dgv.RowCount;
                }
                WordDoc.SaveAs(ref path, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj);
                WordDoc.Close(ref WordObj, ref WordObj, ref WordObj);
                progress.Value = 100;
                MessageBox.Show("数据已经成功导出到:" + savefile.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                progress.Value = 0;
                progress.Visible = false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "友情提示", MessageBoxButtons.OK);
            }
            finally
            {
                word.Quit(ref WordObj, ref WordObj, ref WordObj);
            }
        }
    }
}

// 导入Excel
protected void Button1_Click(object sender, EventArgs e)
{
    DataTable dt = null;
    string path = "", f_folder, f_name;
    int j = 0;
    try
    {
        path = this.FileUpload1.FileName;
        if (path == "")
        {
            Response.Write("<script>alert('请选择Excel文件路径!')</script>");
            return;
        }

        f_name = System.DateTime.Now.ToString();
        f_name = f_name.Replace(" """);
        f_name = f_name.Replace("-""");
        f_name = f_name.Replace(":""");
        f_name = f_name.Replace("/""");
        f_folder = Server.MapPath(@"../upfile/" + f_name + ".xls");
        this.FileUpload1.PostedFile.SaveAs(f_folder);

        // string sheetname = this.txtTable_Name.Text.Trim();
        dt = ExcelDataSource(f_folder, "Sheet1");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Cut c = new Cut();
            c.Name=dt.Rows[i]["优惠券号"].ToString();
            c.Cuts = dt.Rows[i]["折扣"].ToString();
            if (CutsManager.Add(c) == "1")
            {
                j++;
            }
        }
        if (File.Exists(Server.MapPath(@"../upfile/" + f_name + ".xls")))
        {
            File.Delete(f_folder);
        }
        string s = "成功导入输入" + j + "条!";
        if (j == dt.Rows.Count)
        {
            Response.Write("<script>alert('" + s + "')</script>");
        }
    }
    catch
    {
        Response.Write("<script>alert('数据格式出错!')</script>");
    }
}
public DataTable ExcelDataSource(string filepath, string sheetname)
{
    string strConn = String.Empty;
    if (System.IO.Path.GetExtension(filepath).Equals(".xlsx"))
    {
        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES';data source=" + filepath;
    }
    else if (System.IO.Path.GetExtension(filepath).Equals(".xls"))
    {
        //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties=Excel 8.0;";
        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
    }
    OleDbConnection conn = new OleDbConnection(strConn);
    OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn);
    DataTable ds = new DataTable();
    oada.Fill(ds);
    conn.Close();
    return ds;
}
微信小程序扫码登陆

文章评论

1326人参与,0条评论