The p-n junction is the functional element of many electronic and optoelectronic devices, including diodes, bipolar transistors, photodetectors, light-emitting diodes and solar cells. In conventional p-n junctions, the adjacent p- and n-type regions of a semiconductor are formed by chemical doping. Ambipolar semiconductors, such as carbon nanotubes, nanowires and organic molecules, allow for p-n junctions to be configured and modified by electrostatic gating. This electrical control enables a single device to have multiple functionalities. Here, we report ambipolar monolayer WSe2 devices in which two local gates are used to define a p-n junction within the WSe2 sheet. With these electrically tunable p-n junctions, we demonstrate both p-n and n-p diodes with ideality factors better than 2. Under optical excitation, the diodes demonstrate a photodetection responsivity of 210 mA W(-1) and photovoltaic power generation with a peak external quantum efficiency of 0.2%, promising values for a nearly transparent monolayer material in a lateral device geometry. Finally, we demonstrate a light-emitting diode based on monolayer WSe2. These devices provide a building block for ultrathin, flexible and nearly transparent optoelectronic and electronic applications based on ambipolar dichalcogenide materials.